0028668: Point Cloud Rendering - standard selection API returns invalid values
[occt.git] / src / OpenGl / OpenGl_GraphicDriver.cxx
old mode 100755 (executable)
new mode 100644 (file)
index 64637f3..b60b7cd
@@ -13,8 +13,8 @@
 // Alternatively, this file may be used under the terms of Open CASCADE
 // commercial license or contractual agreement.
 
-#ifdef HAVE_CONFIG_H
-  #include <config.h>
+#if defined(_WIN32)
+  #include <windows.h>
 #endif
 
 #include <OpenGl_GraphicDriver.hxx>
 #include <OpenGl_Flipper.hxx>
 #include <OpenGl_GraduatedTrihedron.hxx>
 #include <OpenGl_Group.hxx>
-#include <OpenGl_CView.hxx>
 #include <OpenGl_View.hxx>
 #include <OpenGl_StencilTest.hxx>
 #include <OpenGl_Text.hxx>
-#include <OpenGl_Trihedron.hxx>
 #include <OpenGl_Workspace.hxx>
 
+#include <Aspect_GraphicDeviceDefinitionError.hxx>
+#include <Aspect_IdentDefinitionError.hxx>
+#include <Graphic3d_StructureManager.hxx>
+#include <Message_Messenger.hxx>
+#include <OSD_Environment.hxx>
 #include <Standard_NotImplemented.hxx>
 
-IMPLEMENT_STANDARD_HANDLE(OpenGl_GraphicDriver,Graphic3d_GraphicDriver)
 IMPLEMENT_STANDARD_RTTIEXT(OpenGl_GraphicDriver,Graphic3d_GraphicDriver)
 
+#if defined(_WIN32)
+  #include <WNT_Window.hxx>
+#elif defined(__APPLE__) && !defined(MACOSX_USE_GLX)
+  #include <Cocoa_Window.hxx>
+#else
+  #include <Xw_Window.hxx>
+#endif
+
+#if !defined(_WIN32) && !defined(__ANDROID__) && !defined(__QNX__) && (!defined(__APPLE__) || defined(MACOSX_USE_GLX))
+  #include <X11/Xlib.h> // XOpenDisplay()
+#endif
+
+#if defined(HAVE_EGL) || defined(HAVE_GLES2) || defined(OCCT_UWP) || defined(__ANDROID__) || defined(__QNX__)
+  #include <EGL/egl.h>
+  #ifndef EGL_OPENGL_ES3_BIT
+    #define EGL_OPENGL_ES3_BIT 0x00000040
+  #endif
+#endif
+
 namespace
 {
   static const Handle(OpenGl_Context) TheNullGlCtx;
-};
-
-// Pour eviter de "mangler" MetaGraphicDriverFactory, le nom de la
-// fonction qui cree un Graphic3d_GraphicDriver.
-// En effet, ce nom est recherche par la methode DlSymb de la
-// classe OSD_SharedLibrary dans la methode SetGraphicDriver de la
-// classe Graphic3d_GraphicDevice
-extern "C" {
-#if defined(_MSC_VER) // disable MS VC++ warning on C-style function returning C++ object
-  #pragma warning(push)
-  #pragma warning(disable:4190)
-#endif
-  Standard_EXPORT Handle(Graphic3d_GraphicDriver) MetaGraphicDriverFactory (const Standard_CString theShrName)
+
+#if defined(HAVE_EGL) || defined(HAVE_GLES2) || defined(OCCT_UWP) || defined(__ANDROID__) || defined(__QNX__)
+  //! Wrapper over eglChooseConfig() called with preferred defaults.
+  static EGLConfig chooseEglSurfConfig (EGLDisplay theDisplay)
   {
-    Handle(OpenGl_GraphicDriver) aDriver = new OpenGl_GraphicDriver (theShrName);
-    return aDriver;
+    EGLint aConfigAttribs[] =
+    {
+      EGL_RED_SIZE,     8,
+      EGL_GREEN_SIZE,   8,
+      EGL_BLUE_SIZE,    8,
+      EGL_ALPHA_SIZE,   0,
+      EGL_DEPTH_SIZE,   24,
+      EGL_STENCIL_SIZE, 8,
+    #if defined(GL_ES_VERSION_2_0)
+      EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
+    #else
+      EGL_RENDERABLE_TYPE, EGL_OPENGL_BIT,
+    #endif
+      EGL_NONE
+    };
+
+    EGLConfig aCfg = NULL;
+    EGLint aNbConfigs = 0;
+    for (Standard_Integer aGlesVer = 3; aGlesVer >= 2; --aGlesVer)
+    {
+    #if defined(GL_ES_VERSION_2_0)
+      aConfigAttribs[6 * 2 + 1] = aGlesVer == 3 ? EGL_OPENGL_ES3_BIT : EGL_OPENGL_ES2_BIT;
+    #else
+      if (aGlesVer == 2)
+      {
+        break;
+      }
+    #endif
+
+      if (eglChooseConfig (theDisplay, aConfigAttribs, &aCfg, 1, &aNbConfigs) == EGL_TRUE
+       && aCfg != NULL)
+      {
+        return aCfg;
+      }
+      eglGetError();
+
+      aConfigAttribs[4 * 2 + 1] = 16; // try config with smaller depth buffer
+      if (eglChooseConfig (theDisplay, aConfigAttribs, &aCfg, 1, &aNbConfigs) == EGL_TRUE
+       && aCfg != NULL)
+      {
+        return aCfg;
+      }
+      eglGetError();
+    }
+    return aCfg;
   }
-#if defined(_MSC_VER)
-  #pragma warning(pop)
 #endif
 }
 
@@ -63,526 +116,701 @@ extern "C" {
 // function : OpenGl_GraphicDriver
 // purpose  :
 // =======================================================================
-OpenGl_GraphicDriver::OpenGl_GraphicDriver (const Handle(Aspect_DisplayConnection)& theDisplayConnection)
-: Graphic3d_GraphicDriver ("TKOpenGl"),
-  myCaps           (new OpenGl_Caps()),
-  myMapOfView      (1, NCollection_BaseAllocator::CommonBaseAllocator()),
-  myMapOfWS        (1, NCollection_BaseAllocator::CommonBaseAllocator()),
-  myMapOfStructure (1, NCollection_BaseAllocator::CommonBaseAllocator()),
-  myUserDrawCallback (NULL),
-  myTempText (new OpenGl_Text())
-{
-  Begin (theDisplayConnection);
-}
-
-// =======================================================================
-// function : OpenGl_GraphicDriver
-// purpose  :
-// =======================================================================
-OpenGl_GraphicDriver::OpenGl_GraphicDriver (const Standard_CString theShrName)
-: Graphic3d_GraphicDriver (theShrName),
+OpenGl_GraphicDriver::OpenGl_GraphicDriver (const Handle(Aspect_DisplayConnection)& theDisp,
+                                            const Standard_Boolean                  theToInitialize)
+: Graphic3d_GraphicDriver (theDisp),
+  myIsOwnContext (Standard_False),
+#if defined(HAVE_EGL) || defined(HAVE_GLES2) || defined(OCCT_UWP) || defined(__ANDROID__) || defined(__QNX__)
+  myEglDisplay ((Aspect_Display )EGL_NO_DISPLAY),
+  myEglContext ((Aspect_RenderingContext )EGL_NO_CONTEXT),
+  myEglConfig  (NULL),
+#endif
   myCaps           (new OpenGl_Caps()),
   myMapOfView      (1, NCollection_BaseAllocator::CommonBaseAllocator()),
-  myMapOfWS        (1, NCollection_BaseAllocator::CommonBaseAllocator()),
-  myMapOfStructure (1, NCollection_BaseAllocator::CommonBaseAllocator()),
-  myUserDrawCallback (NULL),
-  myTempText (new OpenGl_Text())
+  myMapOfStructure (1, NCollection_BaseAllocator::CommonBaseAllocator())
 {
-  //
-}
+#if !defined(_WIN32) && !defined(__ANDROID__) && !defined(__QNX__) && (!defined(__APPLE__) || defined(MACOSX_USE_GLX))
+  if (myDisplayConnection.IsNull())
+  {
+    //throw Aspect_GraphicDeviceDefinitionError("OpenGl_GraphicDriver: cannot connect to X server!");
+    return;
+  }
 
-// =======================================================================
-// function : UserDrawCallback
-// purpose  :
-// =======================================================================
-OpenGl_GraphicDriver::OpenGl_UserDrawCallback_t& OpenGl_GraphicDriver::UserDrawCallback()
-{
-  return myUserDrawCallback;
-}
+  Display* aDisplay = myDisplayConnection->GetDisplay();
+  Bool toSync = ::getenv ("CSF_GraphicSync") != NULL
+             || ::getenv ("CALL_SYNCHRO_X")  != NULL;
+  XSynchronize (aDisplay, toSync);
 
-// =======================================================================
-// function : DefaultTextHeight
-// purpose  :
-// =======================================================================
-Standard_ShortReal OpenGl_GraphicDriver::DefaultTextHeight() const
-{
-  return 16.;
+#if !defined(HAVE_EGL) && !defined(HAVE_GLES2)
+  // does the server know about OpenGL & GLX?
+  int aDummy;
+  if (!XQueryExtension (aDisplay, "GLX", &aDummy, &aDummy, &aDummy))
+  {
+    ::Message::DefaultMessenger()->Send ("OpenGl_GraphicDriver, this system doesn't appear to support OpenGL!", Message_Warning);
+  }
+#endif
+#endif
+  if (theToInitialize
+  && !InitContext())
+  {
+    throw Aspect_GraphicDeviceDefinitionError("OpenGl_GraphicDriver: default context can not be initialized!");
+  }
 }
 
 // =======================================================================
-// function : EnableVBO
+// function : ~OpenGl_GraphicDriver
 // purpose  :
 // =======================================================================
-void OpenGl_GraphicDriver::EnableVBO (const Standard_Boolean theToTurnOn)
+OpenGl_GraphicDriver::~OpenGl_GraphicDriver()
 {
-  myCaps->vboDisable = !theToTurnOn;
+  ReleaseContext();
 }
 
 // =======================================================================
-// function : GetSharedContext
+// function : ReleaseContext
 // purpose  :
 // =======================================================================
-const Handle(OpenGl_Context)& OpenGl_GraphicDriver::GetSharedContext() const
+void OpenGl_GraphicDriver::ReleaseContext()
 {
-  if (myMapOfWS.IsEmpty())
+  Handle(OpenGl_Context) aCtxShared;
+  for (NCollection_Map<Handle(OpenGl_View)>::Iterator aViewIter (myMapOfView);
+       aViewIter.More(); aViewIter.Next())
   {
-    return TheNullGlCtx;
+    const Handle(OpenGl_View)& aView = aViewIter.Value();
+    const Handle(OpenGl_Window)& aWindow = aView->GlWindow();
+    if (aWindow.IsNull())
+    {
+      continue;
+    }
+
+    const Handle(OpenGl_Context)& aCtx = aWindow->GetGlContext();
+    if (aCtx->MakeCurrent()
+     && aCtxShared.IsNull())
+    {
+      aCtxShared = aCtx;
+    }
   }
 
-  NCollection_DataMap<Standard_Integer, Handle(OpenGl_Workspace)>::Iterator anIter (myMapOfWS);
-  return anIter.Value()->GetGlContext();
-}
+  if (!aCtxShared.IsNull())
+  {
+    aCtxShared->MakeCurrent();
+  }
+  for (NCollection_Map<Handle(OpenGl_View)>::Iterator aViewIter (myMapOfView);
+       aViewIter.More(); aViewIter.Next())
+  {
+    const Handle(OpenGl_View)& aView = aViewIter.Value();
+    aView->ReleaseGlResources (aCtxShared);
+  }
 
-// =======================================================================
-// function : MemoryInfo
-// purpose  :
-// =======================================================================
-Standard_Boolean OpenGl_GraphicDriver::MemoryInfo (Standard_Size&           theFreeBytes,
-                                                   TCollection_AsciiString& theInfo) const
-{
-  // this is extra work (for OpenGl_Context initialization)...
-  OpenGl_Context aGlCtx;
-  if (!aGlCtx.Init())
+  for (NCollection_DataMap<Standard_Integer, OpenGl_Structure*>::Iterator aStructIt (myMapOfStructure);
+       aStructIt.More (); aStructIt.Next())
   {
-    return Standard_False;
+    OpenGl_Structure* aStruct = aStructIt.ChangeValue();
+    aStruct->ReleaseGlResources (aCtxShared);
   }
-  theFreeBytes = aGlCtx.AvailableMemory();
-  theInfo      = aGlCtx.MemoryInfo();
-  return !theInfo.IsEmpty();
-}
 
-// =======================================================================
-// function : SetImmediateModeDrawToFront
-// purpose  :
-// =======================================================================
-Standard_Boolean OpenGl_GraphicDriver::SetImmediateModeDrawToFront (const Graphic3d_CView& theCView,
-                                                                    const Standard_Boolean theDrawToFrontBuffer)
-{
-  if (theCView.ViewId == -1)
+  const bool isDeviceLost = !myMapOfStructure.IsEmpty();
+  for (NCollection_Map<Handle(OpenGl_View)>::Iterator aViewIter (myMapOfView);
+       aViewIter.More(); aViewIter.Next())
   {
-    return Standard_False;
+    const Handle(OpenGl_View)& aView = aViewIter.Value();
+    if (isDeviceLost)
+    {
+      aView->StructureManager()->SetDeviceLost();
+    }
+
+    const Handle(OpenGl_Window)& aWindow = aView->GlWindow();
+    if (aWindow.IsNull())
+    {
+      continue;
+    }
+
+    aWindow->GetGlContext()->forcedRelease();
   }
 
-  const OpenGl_CView* aCView = (const OpenGl_CView* )theCView.ptrView;
-  if (aCView != NULL)
+#if defined(HAVE_EGL) || defined(HAVE_GLES2) || defined(OCCT_UWP) || defined(__ANDROID__) || defined(__QNX__)
+  if (myIsOwnContext)
   {
-    return aCView->WS->SetImmediateModeDrawToFront (theDrawToFrontBuffer);
+    if (myEglContext != (Aspect_RenderingContext )EGL_NO_CONTEXT)
+    {
+      if (eglMakeCurrent ((EGLDisplay )myEglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT) != EGL_TRUE)
+      {
+        ::Message::DefaultMessenger()->Send ("OpenGl_GraphicDriver, FAILED to release OpenGL context!", Message_Warning);
+      }
+      eglDestroyContext ((EGLDisplay )myEglDisplay, (EGLContext )myEglContext);
+    }
+
+    if (myEglDisplay != (Aspect_Display )EGL_NO_DISPLAY)
+    {
+      if (eglTerminate ((EGLDisplay )myEglDisplay) != EGL_TRUE)
+      {
+        ::Message::DefaultMessenger()->Send ("OpenGl_GraphicDriver, EGL, eglTerminate FAILED!", Message_Warning);
+      }
+    }
   }
-  return Standard_False;
+
+  myEglDisplay = (Aspect_Display )EGL_NO_DISPLAY;
+  myEglContext = (Aspect_RenderingContext )EGL_NO_CONTEXT;
+  myEglConfig  = NULL;
+#endif
+  myIsOwnContext = Standard_False;
 }
 
 // =======================================================================
-// function : GetOpenClDeviceInfo
-// purpose  : Returns information about device used for computations
+// function : InitContext
+// purpose  :
 // =======================================================================
-#ifndef HAVE_OPENCL
-
-Standard_Boolean OpenGl_GraphicDriver::GetOpenClDeviceInfo (const Graphic3d_CView&,
-  NCollection_DataMap<TCollection_AsciiString, TCollection_AsciiString>&)
-{
-  return Standard_False;
-}
-
-#else
-
-Standard_Boolean OpenGl_GraphicDriver::GetOpenClDeviceInfo (const Graphic3d_CView& theCView,
-  NCollection_DataMap<TCollection_AsciiString, TCollection_AsciiString>& theInfo)
+Standard_Boolean OpenGl_GraphicDriver::InitContext()
 {
+  ReleaseContext();
+#if defined(HAVE_EGL) || defined(HAVE_GLES2) || defined(OCCT_UWP) || defined(__ANDROID__) || defined(__QNX__)
 
-  if (theCView.ViewId == -1 || theCView.ptrView == NULL)
+#if !defined(_WIN32) && !defined(__ANDROID__) && !defined(__QNX__) && (!defined(__APPLE__) || defined(MACOSX_USE_GLX))
+  if (myDisplayConnection.IsNull())
   {
     return Standard_False;
   }
-
-  return reinterpret_cast<const OpenGl_CView*> (theCView.ptrView)->WS->GetOpenClDeviceInfo (theInfo);
-}
-
+  Display* aDisplay = myDisplayConnection->GetDisplay();
+  myEglDisplay = (Aspect_Display )eglGetDisplay (aDisplay);
+#else
+  myEglDisplay = (Aspect_Display )eglGetDisplay (EGL_DEFAULT_DISPLAY);
 #endif
+  if ((EGLDisplay )myEglDisplay == EGL_NO_DISPLAY)
+  {
+    ::Message::DefaultMessenger()->Send ("Error: no EGL display!", Message_Fail);
+    return Standard_False;
+  }
 
-// =======================================================================
-// function : BeginAddMode
-// purpose  :
-// =======================================================================
-Standard_Boolean OpenGl_GraphicDriver::BeginAddMode (const Graphic3d_CView& theCView)
-{
-  if (theCView.ViewId == -1)
+  EGLint aVerMajor = 0; EGLint aVerMinor = 0;
+  if (eglInitialize ((EGLDisplay )myEglDisplay, &aVerMajor, &aVerMinor) != EGL_TRUE)
   {
+    ::Message::DefaultMessenger()->Send ("Error: EGL display is unavailable!", Message_Fail);
     return Standard_False;
   }
 
-  const OpenGl_CView* aCView = (const OpenGl_CView* )theCView.ptrView;
-  if (aCView != NULL && aCView->WS->BeginAddMode())
+  myEglConfig = chooseEglSurfConfig ((EGLDisplay )myEglDisplay);
+  if (myEglConfig == NULL)
   {
-    myImmediateWS = aCView->WS;
-    return Standard_True;
+    ::Message::DefaultMessenger()->Send ("Error: EGL does not provide compatible configurations!", Message_Fail);
+    return Standard_False;
   }
 
-  return Standard_False;
-}
+#if defined(GL_ES_VERSION_2_0)
+  EGLint anEglCtxAttribs3[] = { EGL_CONTEXT_CLIENT_VERSION, 3, EGL_NONE, EGL_NONE };
+  EGLint anEglCtxAttribs2[] = { EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE, EGL_NONE };
+  if (eglBindAPI (EGL_OPENGL_ES_API) != EGL_TRUE)
+  {
+    ::Message::DefaultMessenger()->Send ("Error: EGL does not provide OpenGL ES client!", Message_Fail);
+    return Standard_False;
+  }
+  myEglContext = (Aspect_RenderingContext )eglCreateContext ((EGLDisplay )myEglDisplay, myEglConfig, EGL_NO_CONTEXT, anEglCtxAttribs3);
+  if ((EGLContext )myEglContext == EGL_NO_CONTEXT)
+  {
+    myEglContext = (Aspect_RenderingContext )eglCreateContext ((EGLDisplay )myEglDisplay, myEglConfig, EGL_NO_CONTEXT, anEglCtxAttribs2);
+  }
+#else
+  EGLint* anEglCtxAttribs = NULL;
+  if (eglBindAPI (EGL_OPENGL_API) != EGL_TRUE)
+  {
+    ::Message::DefaultMessenger()->Send ("Error: EGL does not provide OpenGL client!", Message_Fail);
+    return Standard_False;
+  }
+  myEglContext = (Aspect_RenderingContext )eglCreateContext ((EGLDisplay )myEglDisplay, myEglConfig, EGL_NO_CONTEXT, anEglCtxAttribs);
+#endif
 
-// =======================================================================
-// function : EndAddMode
-// purpose  :
-// =======================================================================
-void OpenGl_GraphicDriver::EndAddMode()
-{
-  if (!myImmediateWS.IsNull())
+  if ((EGLContext )myEglContext == EGL_NO_CONTEXT)
   {
-    myImmediateWS->EndAddMode();
-    myImmediateWS.Nullify();
+    ::Message::DefaultMessenger()->Send ("Error: EGL is unable to create OpenGL context!", Message_Fail);
+    return Standard_False;
   }
+  // eglMakeCurrent() fails or even crash with EGL_NO_SURFACE on some implementations
+  //if (eglMakeCurrent ((EGLDisplay )myEglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, (EGLContext )myEglContext) != EGL_TRUE)
+  //{
+  //  ::Message::DefaultMessenger()->Send ("Error: EGL is unable bind OpenGL context!", Message_Fail);
+  //  return Standard_False;
+  //}
+#endif
+  myIsOwnContext = Standard_True;
+  return Standard_True;
 }
 
+#if defined(HAVE_EGL) || defined(HAVE_GLES2) || defined(OCCT_UWP) || defined(__ANDROID__) || defined(__QNX__)
 // =======================================================================
-// function : BeginImmediatMode
+// function : InitEglContext
 // purpose  :
 // =======================================================================
-Standard_Boolean OpenGl_GraphicDriver::BeginImmediatMode (const Graphic3d_CView& theCView,
-                                                          const Aspect_CLayer2d& /*theCUnderLayer*/,
-                                                          const Aspect_CLayer2d& /*theCOverLayer*/,
-                                                          const Standard_Boolean theDoubleBuffer,
-                                                          const Standard_Boolean theRetainMode)
+Standard_Boolean OpenGl_GraphicDriver::InitEglContext (Aspect_Display          theEglDisplay,
+                                                       Aspect_RenderingContext theEglContext,
+                                                       void*                   theEglConfig)
 {
-  if (theCView.ViewId == -1)
+  ReleaseContext();
+#if !defined(_WIN32) && !defined(__ANDROID__) && !defined(__QNX__) && (!defined(__APPLE__) || defined(MACOSX_USE_GLX))
+  if (myDisplayConnection.IsNull())
   {
     return Standard_False;
   }
+#endif
 
-  const OpenGl_CView* aCView = (const OpenGl_CView* )theCView.ptrView;
-  if (aCView != NULL && aCView->WS->BeginImmediatMode (theCView, theDoubleBuffer, theRetainMode))
+  if ((EGLDisplay )theEglDisplay == EGL_NO_DISPLAY
+   || (EGLContext )theEglContext == EGL_NO_CONTEXT)
   {
-    myImmediateWS = aCView->WS;
-    return Standard_True;
+    return Standard_False;
   }
-
-  return Standard_False;
+  myEglDisplay = theEglDisplay;
+  myEglContext = theEglContext;
+  myEglConfig  = theEglConfig;
+  if (theEglConfig == NULL)
+  {
+    myEglConfig = chooseEglSurfConfig ((EGLDisplay )myEglDisplay);
+    if (myEglConfig == NULL)
+    {
+      ::Message::DefaultMessenger()->Send ("Error: EGL does not provide compatible configurations!", Message_Fail);
+      return Standard_False;
+    }
+  }
+  return Standard_True;
 }
+#endif
 
 // =======================================================================
-// function : ClearImmediatMode
+// function : InquireLimit
 // purpose  :
 // =======================================================================
-void OpenGl_GraphicDriver::ClearImmediatMode (const Graphic3d_CView& theCView,
-                                              const Standard_Boolean theToFlush)
+Standard_Integer OpenGl_GraphicDriver::InquireLimit (const Graphic3d_TypeOfLimit theType) const
 {
-  const OpenGl_CView* aCView = (const OpenGl_CView* )theCView.ptrView;
-  if (aCView != NULL)
+  const Handle(OpenGl_Context)& aCtx = GetSharedContext();
+  switch (theType)
   {
-    aCView->WS->ClearImmediatMode (theCView, theToFlush);
+    case Graphic3d_TypeOfLimit_MaxNbLights:
+      return Graphic3d_ShaderProgram::THE_MAX_LIGHTS_DEFAULT;
+    case Graphic3d_TypeOfLimit_MaxNbClipPlanes:
+      return !aCtx.IsNull() ? aCtx->MaxClipPlanes() : 0;
+    case Graphic3d_TypeOfLimit_MaxNbViews:
+      return 10000;
+    case Graphic3d_TypeOfLimit_MaxTextureSize:
+      return !aCtx.IsNull() ? aCtx->MaxTextureSize() : 1024;
+    case Graphic3d_TypeOfLimit_MaxCombinedTextureUnits:
+      return !aCtx.IsNull() ? aCtx->MaxCombinedTextureUnits() : 1;
+    case Graphic3d_TypeOfLimit_MaxMsaa:
+      return !aCtx.IsNull() ? aCtx->MaxMsaaSamples() : 0;
+    case Graphic3d_TypeOfLimit_MaxViewDumpSizeX:
+      return !aCtx.IsNull() ? aCtx->MaxDumpSizeX() : 1024;
+    case Graphic3d_TypeOfLimit_MaxViewDumpSizeY:
+      return !aCtx.IsNull() ? aCtx->MaxDumpSizeY() : 1024;
+    case Graphic3d_TypeOfLimit_HasRayTracing:
+      return (!aCtx.IsNull() && aCtx->HasRayTracing()) ? 1 : 0;
+    case Graphic3d_TypeOfLimit_HasRayTracingTextures:
+      return (!aCtx.IsNull() && aCtx->HasRayTracingTextures()) ? 1 : 0;
+    case Graphic3d_TypeOfLimit_HasRayTracingAdaptiveSampling:
+      return (!aCtx.IsNull() && aCtx->HasRayTracingAdaptiveSampling()) ? 1 : 0;
+    case Graphic3d_TypeOfLimit_HasRayTracingAdaptiveSamplingAtomic:
+      return (!aCtx.IsNull() && aCtx->HasRayTracingAdaptiveSamplingAtomic()) ? 1 : 0;
+    case Graphic3d_TypeOfLimit_HasBlendedOit:
+      return (!aCtx.IsNull()
+            && aCtx->hasDrawBuffers != OpenGl_FeatureNotAvailable
+            && (aCtx->hasFloatBuffer != OpenGl_FeatureNotAvailable || aCtx->hasHalfFloatBuffer != OpenGl_FeatureNotAvailable)) ? 1 : 0;
+    case Graphic3d_TypeOfLimit_HasBlendedOitMsaa:
+      return (!aCtx.IsNull()
+            && aCtx->hasSampleVariables != OpenGl_FeatureNotAvailable
+            && (InquireLimit (Graphic3d_TypeOfLimit_HasBlendedOit) == 1)) ? 1 : 0;
+    case Graphic3d_TypeOfLimit_HasFlatShading:
+      return !aCtx.IsNull() && aCtx->hasFlatShading != OpenGl_FeatureNotAvailable ? 1 : 0;
+    case Graphic3d_TypeOfLimit_IsWorkaroundFBO:
+      return !aCtx.IsNull() && aCtx->MaxTextureSize() != aCtx->MaxDumpSizeX() ? 1 : 0;
+    case Graphic3d_TypeOfLimit_HasMeshEdges:
+      return !aCtx.IsNull() && aCtx->hasGeometryStage != OpenGl_FeatureNotAvailable ? 1 : 0;
+    case Graphic3d_TypeOfLimit_NB:
+      return 0;
   }
+  return 0;
 }
 
 // =======================================================================
-// function : DrawStructure
+// function : DefaultTextHeight
 // purpose  :
 // =======================================================================
-void OpenGl_GraphicDriver::DrawStructure (const Graphic3d_CStructure& theCStructure)
+Standard_ShortReal OpenGl_GraphicDriver::DefaultTextHeight() const
 {
-  OpenGl_Structure* aStructure = (OpenGl_Structure* )&theCStructure;
-  if (!myImmediateWS.IsNull())
-  {
-    myImmediateWS->DrawStructure (aStructure);
-  }
+  return 16.;
 }
 
 // =======================================================================
-// function : EndImmediatMode
+// function : EnableVBO
 // purpose  :
 // =======================================================================
-void OpenGl_GraphicDriver::EndImmediatMode (const Standard_Integer )
+void OpenGl_GraphicDriver::EnableVBO (const Standard_Boolean theToTurnOn)
 {
-  if (!myImmediateWS.IsNull())
-  {
-    myImmediateWS->EndImmediatMode();
-    myImmediateWS.Nullify();
-  }
+  myCaps->vboDisable = !theToTurnOn;
 }
 
 // =======================================================================
-// function : Print
+// function : GetSharedContext
 // purpose  :
 // =======================================================================
-Standard_Boolean OpenGl_GraphicDriver::Print (const Graphic3d_CView& theCView,
-                                              const Aspect_CLayer2d& theCUnderLayer,
-                                              const Aspect_CLayer2d& theCOverLayer,
-                                              const Aspect_Handle    thePrintDC,
-                                              const Standard_Boolean theToShowBackground,
-                                              const Standard_CString theFilename,
-                                              const Aspect_PrintAlgo thePrintAlgorithm,
-                                              const Standard_Real    theScaleFactor) const
+const Handle(OpenGl_Context)& OpenGl_GraphicDriver::GetSharedContext (bool theBound) const
 {
-  const OpenGl_CView* aCView = (const OpenGl_CView* )theCView.ptrView;
-  if (aCView == NULL
-   || !myPrintContext.IsNull())
+  if (myMapOfView.IsEmpty())
   {
-    return Standard_False;
+    return TheNullGlCtx;
   }
 
-  Standard_Boolean isPrinted = Standard_False;
-  myPrintContext = new OpenGl_PrinterContext();
-#ifdef _WIN32
-  isPrinted = aCView->WS->Print (myPrintContext,
-                                 theCView,
-                                 theCUnderLayer,
-                                 theCOverLayer,
-                                 thePrintDC,
-                                 theToShowBackground,
-                                 theFilename,
-                                 thePrintAlgorithm,
-                                 theScaleFactor);
-#else
-  Standard_NotImplemented::Raise ("OpenGl_GraphicDriver::Print is implemented only on Windows");
-#endif
-  myPrintContext.Nullify();
-  return isPrinted;
-}
+  for (NCollection_Map<Handle(OpenGl_View)>::Iterator aViewIter (myMapOfView); aViewIter.More(); aViewIter.Next())
+  {
+    if (const Handle(OpenGl_Window)& aWindow = aViewIter.Value()->GlWindow())
+    {
+      if (!theBound)
+      {
+        return aWindow->GetGlContext();
+      }
+      else if (aWindow->GetGlContext()->IsCurrent())
+      {
+        return aWindow->GetGlContext();
+      }
+    }
+  }
 
-void OpenGl_GraphicDriver::SetStencilTestOptions (const Graphic3d_CGroup& theCGroup,
-                                                  const Standard_Boolean theIsEnabled)
-{
-  OpenGl_StencilTest* aStencilTest = new OpenGl_StencilTest();
-  aStencilTest->SetOptions (theIsEnabled);
-  ((OpenGl_Group* )theCGroup.ptrGroup)->AddElement (aStencilTest);
+  return TheNullGlCtx;
 }
 
 // =======================================================================
-// function : Text
+// function : MemoryInfo
 // purpose  :
 // =======================================================================
-void OpenGl_GraphicDriver::Text (const Graphic3d_CGroup&                 theCGroup,
-                                 const TCollection_ExtendedString&       theText,
-                                 const Graphic3d_Vertex&                 thePoint,
-                                 const Standard_Real                     theHeight,
-                                 const Quantity_PlaneAngle               /*theAngle*/,
-                                 const Graphic3d_TextPath                /*theTp*/,
-                                 const Graphic3d_HorizontalTextAlignment theHta,
-                                 const Graphic3d_VerticalTextAlignment   theVta,
-                                 const Standard_Boolean                  /*theToEvalMinMax*/)
+Standard_Boolean OpenGl_GraphicDriver::MemoryInfo (Standard_Size&           theFreeBytes,
+                                                   TCollection_AsciiString& theInfo) const
 {
-  if (theCGroup.ptrGroup == NULL)
+  // this is extra work (for OpenGl_Context initialization)...
+  OpenGl_Context aGlCtx;
+  if (!aGlCtx.Init())
   {
-    return;
+    return Standard_False;
   }
-
-  OpenGl_TextParam aParams;
-  aParams.Height = int ((theHeight < 2.0) ? DefaultTextHeight() : theHeight);
-  aParams.HAlign = theHta;
-  aParams.VAlign = theVta;
-  const OpenGl_Vec3 aPoint (thePoint.X(), thePoint.Y(), thePoint.Z());
-  OpenGl_Text* aText = new OpenGl_Text (theText, aPoint, aParams);
-  ((OpenGl_Group* )theCGroup.ptrGroup)->AddElement (aText);
+  theFreeBytes = aGlCtx.AvailableMemory();
+  theInfo      = aGlCtx.MemoryInfo();
+  return !theInfo.IsEmpty();
 }
 
 // =======================================================================
-// function : Text
-// purpose  : Wrapper CString -> TCollection_ExtendedString
+// function : SetBuffersNoSwap
+// purpose  :
 // =======================================================================
-void OpenGl_GraphicDriver::Text (const Graphic3d_CGroup&                 theCGroup,
-                                 const Standard_CString                  theText,
-                                 const Graphic3d_Vertex&                 thePoint,
-                                 const Standard_Real                     theHeight,
-                                 const Quantity_PlaneAngle               theAngle,
-                                 const Graphic3d_TextPath                theTp,
-                                 const Graphic3d_HorizontalTextAlignment theHta,
-                                 const Graphic3d_VerticalTextAlignment   theVta,
-                                 const Standard_Boolean                  theToEvalMinMax)
+void OpenGl_GraphicDriver::SetBuffersNoSwap (const Standard_Boolean theIsNoSwap)
 {
-  OpenGl_GraphicDriver::Text (theCGroup, TCollection_ExtendedString (theText),
-                              thePoint, theHeight, theAngle, theTp, theHta, theVta, theToEvalMinMax);
+  myCaps->buffersNoSwap = theIsNoSwap;
 }
 
 // =======================================================================
-// function : Text
-// purpose  : Wrapper CString -> TCollection_ExtendedString
+// function : TextSize
+// purpose  :
 // =======================================================================
-void OpenGl_GraphicDriver::Text (const Graphic3d_CGroup& theCGroup,
-                                 const Standard_CString  theText,
-                                 const Graphic3d_Vertex& thePoint,
-                                 const Standard_Real     theHeight,
-                                 const Standard_Boolean  theToEvalMinMax)
+void OpenGl_GraphicDriver::TextSize (const Handle(Graphic3d_CView)& theView,
+                                     const Standard_CString         theText,
+                                     const Standard_ShortReal       theHeight,
+                                     Standard_ShortReal&            theWidth,
+                                     Standard_ShortReal&            theAscent,
+                                     Standard_ShortReal&            theDescent) const
 {
-  OpenGl_GraphicDriver::Text (theCGroup, TCollection_ExtendedString (theText), thePoint, theHeight, theToEvalMinMax);
-}
+  const Handle(OpenGl_Context)& aCtx = GetSharedContext();
+  if (aCtx.IsNull())
+  {
+    return;
+  }
 
-// =======================================================================
-// function : Text
-// purpose  : Wrapper with default values
-// =======================================================================
-void OpenGl_GraphicDriver::Text (const Graphic3d_CGroup&           theCGroup,
-                                 const TCollection_ExtendedString& theText,
-                                 const Graphic3d_Vertex&           thePoint,
-                                 const Standard_Real               theHeight,
-                                 const Standard_Boolean            theToEvalMinMax)
-{
-  OpenGl_GraphicDriver::Text (theCGroup,
-                              theText, thePoint, theHeight, 0.0,
-                              Graphic3d_TP_RIGHT, Graphic3d_HTA_LEFT, Graphic3d_VTA_BOTTOM,
-                              theToEvalMinMax);
+  const Standard_ShortReal aHeight = (theHeight < 2.0f) ? DefaultTextHeight() : theHeight;
+  OpenGl_TextParam aTextParam;
+  aTextParam.Height = (int )aHeight;
+  OpenGl_Aspects aTextAspect;
+  TCollection_ExtendedString anExtText = theText;
+  NCollection_String aText (anExtText.ToExtString());
+  OpenGl_Text::StringSize(aCtx, aText, aTextAspect, aTextParam, theView->RenderingParams().Resolution, theWidth, theAscent, theDescent);
 }
 
-// =======================================================================
-// function : ZBufferTriedronSetup
-// purpose  :
-// =======================================================================
-void OpenGl_GraphicDriver::ZBufferTriedronSetup (const Quantity_NameOfColor theXColor,
-                                                 const Quantity_NameOfColor theYColor,
-                                                 const Quantity_NameOfColor theZColor,
-                                                 const Standard_Real        theSizeRatio,
-                                                 const Standard_Real        theAxisDiametr,
-                                                 const Standard_Integer     theNbFacettes)
+//=======================================================================
+//function : AddZLayer
+//purpose  :
+//=======================================================================
+void OpenGl_GraphicDriver::AddZLayer (const Graphic3d_ZLayerId theLayerId)
 {
-  OpenGl_Trihedron::Setup (theXColor, theYColor, theZColor, theSizeRatio, theAxisDiametr, theNbFacettes);
+  if (theLayerId < 1)
+  {
+    Standard_ASSERT_RAISE (theLayerId > 0,
+                           "OpenGl_GraphicDriver::AddZLayer, "
+                           "negative and zero IDs are reserved");
+  }
+
+  myLayerIds.Add (theLayerId);
+
+  // Default z-layer settings
+  myMapOfZLayerSettings.Bind (theLayerId, Graphic3d_ZLayerSettings());
+  addZLayerIndex (theLayerId);
+
+  // Add layer to all views
+  NCollection_Map<Handle(OpenGl_View)>::Iterator aViewIt (myMapOfView);
+  for (; aViewIt.More(); aViewIt.Next())
+  {
+    aViewIt.Value()->AddZLayer (theLayerId);
+  }
 }
 
-// =======================================================================
-// function : TriedronDisplay
-// purpose  :
-// =======================================================================
-void OpenGl_GraphicDriver::TriedronDisplay (const Graphic3d_CView&              theCView,
-                                            const Aspect_TypeOfTriedronPosition thePosition,
-                                            const Quantity_NameOfColor          theColor,
-                                            const Standard_Real                 theScale,
-                                            const Standard_Boolean              theAsWireframe)
+//=======================================================================
+//function : RemoveZLayer
+//purpose  :
+//=======================================================================
+void OpenGl_GraphicDriver::RemoveZLayer (const Graphic3d_ZLayerId theLayerId)
 {
-  const OpenGl_CView* aCView = (const OpenGl_CView* )theCView.ptrView;
-  if (aCView != NULL)
+  Standard_ASSERT_RAISE (theLayerId > 0,
+                         "OpenGl_GraphicDriver::AddZLayer, "
+                         "negative and zero IDs are reserved"
+                         "and can not be removed");
+
+  Standard_ASSERT_RAISE (myLayerIds.Contains (theLayerId),
+                         "OpenGl_GraphicDriver::RemoveZLayer, "
+                         "Layer with theLayerId does not exist");
+
+  // Remove layer from all of the views
+  NCollection_Map<Handle(OpenGl_View)>::Iterator aViewIt (myMapOfView);
+  for (; aViewIt.More(); aViewIt.Next())
+  {
+    aViewIt.Value()->RemoveZLayer (theLayerId);
+  }
+
+  // Unset Z layer for all of the structures.
+  NCollection_DataMap<Standard_Integer, OpenGl_Structure*>::Iterator aStructIt (myMapOfStructure);
+  for( ; aStructIt.More (); aStructIt.Next ())
+  {
+    OpenGl_Structure* aStruct = aStructIt.ChangeValue ();
+    if (aStruct->ZLayer() == theLayerId)
+      aStruct->SetZLayer (Graphic3d_ZLayerId_Default);
+  }
+
+  // Remove index
+  for (TColStd_SequenceOfInteger::Iterator aLayerIt (myLayerSeq); aLayerIt.More(); aLayerIt.Next())
   {
-    aCView->View->TriedronDisplay (aCView->WS->GetGlContext(), thePosition, theColor, theScale, theAsWireframe);
+    if (aLayerIt.Value() == theLayerId)
+    {
+      myLayerSeq.Remove (aLayerIt);
+      break;
+    }
   }
+
+  myMapOfZLayerSettings.UnBind (theLayerId);
+  myLayerIds.Remove  (theLayerId);
 }
 
-// =======================================================================
-// function : TriedronErase
-// purpose  :
-// =======================================================================
-void OpenGl_GraphicDriver::TriedronErase (const Graphic3d_CView& theCView)
+//=======================================================================
+//function : SetZLayerSettings
+//purpose  :
+//=======================================================================
+void OpenGl_GraphicDriver::SetZLayerSettings (const Graphic3d_ZLayerId theLayerId,
+                                              const Graphic3d_ZLayerSettings& theSettings)
 {
-  const OpenGl_CView* aCView = (const OpenGl_CView* )theCView.ptrView;
-  if (aCView != NULL)
+  base_type::SetZLayerSettings (theLayerId, theSettings);
+
+  // Change Z layer settings in all managed views
+  for (NCollection_Map<Handle(OpenGl_View)>::Iterator aViewIt (myMapOfView); aViewIt.More(); aViewIt.Next())
   {
-    aCView->View->TriedronErase (aCView->WS->GetGlContext());
+    aViewIt.Value()->SetZLayerSettings (theLayerId, theSettings);
   }
 }
 
 // =======================================================================
-// function : TriedronEcho
+// function : Structure
 // purpose  :
 // =======================================================================
-void OpenGl_GraphicDriver::TriedronEcho (const Graphic3d_CView& ,
-                                         const Aspect_TypeOfTriedronEcho )
+Handle(Graphic3d_CStructure) OpenGl_GraphicDriver::CreateStructure (const Handle(Graphic3d_StructureManager)& theManager)
 {
-  // do nothing
+  Handle(OpenGl_Structure) aStructure = new OpenGl_Structure (theManager);
+  myMapOfStructure.Bind (aStructure->Id, aStructure.operator->());
+  return aStructure;
 }
 
 // =======================================================================
-// function : Environment
+// function : Structure
 // purpose  :
 // =======================================================================
-void OpenGl_GraphicDriver::Environment (const Graphic3d_CView& theCView)
+void OpenGl_GraphicDriver::RemoveStructure (Handle(Graphic3d_CStructure)& theCStructure)
 {
-  const OpenGl_CView* aCView = (const OpenGl_CView* )theCView.ptrView;
-  if (aCView == NULL)
+  OpenGl_Structure* aStructure = NULL;
+  if (!myMapOfStructure.Find (theCStructure->Id, aStructure))
   {
     return;
   }
 
-  aCView->View->SetTextureEnv    (aCView->WS->GetGlContext(), theCView.Context.TextureEnv);
-  aCView->View->SetSurfaceDetail ((Visual3d_TypeOfSurfaceDetail)theCView.Context.SurfaceDetail);
+  myMapOfStructure.UnBind (theCStructure->Id);
+  aStructure->Release (GetSharedContext());
+  theCStructure.Nullify();
 }
 
 // =======================================================================
-// function : BackgroundImage
+// function : View
 // purpose  :
 // =======================================================================
-void OpenGl_GraphicDriver::BackgroundImage (const Standard_CString  theFileName,
-                                            const Graphic3d_CView&  theCView,
-                                            const Aspect_FillMethod theFillStyle)
+Handle(Graphic3d_CView) OpenGl_GraphicDriver::CreateView (const Handle(Graphic3d_StructureManager)& theMgr)
 {
-  const OpenGl_CView* aCView = (const OpenGl_CView* )theCView.ptrView;
-  if (aCView != NULL)
+  Handle(OpenGl_View) aView = new OpenGl_View (theMgr, this, myCaps, &myStateCounter);
+
+  myMapOfView.Add (aView);
+
+  for (TColStd_SequenceOfInteger::Iterator aLayerIt (myLayerSeq); aLayerIt.More(); aLayerIt.Next())
   {
-    aCView->View->CreateBackgroundTexture (theFileName, theFillStyle);
+    const Graphic3d_ZLayerId        aLayerID  = aLayerIt.Value();
+    const Graphic3d_ZLayerSettings& aSettings = myMapOfZLayerSettings.Find (aLayerID);
+    aView->AddZLayer         (aLayerID);
+    aView->SetZLayerSettings (aLayerID, aSettings);
   }
+
+  return aView;
 }
 
 // =======================================================================
-// function : SetBgImageStyle
+// function : RemoveView
 // purpose  :
 // =======================================================================
-void OpenGl_GraphicDriver::SetBgImageStyle (const Graphic3d_CView&  theCView,
-                                            const Aspect_FillMethod theFillStyle)
+void OpenGl_GraphicDriver::RemoveView (const Handle(Graphic3d_CView)& theView)
 {
-  const OpenGl_CView* aCView = (const OpenGl_CView* )theCView.ptrView;
-  if (aCView != NULL)
+  Handle(OpenGl_Context) aCtx = GetSharedContext();
+  Handle(OpenGl_View) aView   = Handle(OpenGl_View)::DownCast (theView);
+  if (aView.IsNull())
   {
-    aCView->View->SetBackgroundTextureStyle (theFillStyle);
+    return;
   }
-}
 
-// =======================================================================
-// function : SetBgGradientStyle
-// purpose  :
-// =======================================================================
-void OpenGl_GraphicDriver::SetBgGradientStyle (const Graphic3d_CView&          theCView,
-                                               const Aspect_GradientFillMethod theFillType)
-{
-  const OpenGl_CView* aCView = (const OpenGl_CView* )theCView.ptrView;
-  if (aCView != NULL)
+  if (!myMapOfView.Remove (aView))
   {
-    aCView->View->SetBackgroundGradientType (theFillType);
+    return;
   }
-}
 
-// =======================================================================
-// function : GraduatedTrihedronDisplay
-// purpose  :
-// =======================================================================
-void OpenGl_GraphicDriver::GraduatedTrihedronDisplay (const Graphic3d_CView&               theCView,
-                                                      const Graphic3d_CGraduatedTrihedron& theCubic)
-{
-  const OpenGl_CView* aCView = (const OpenGl_CView* )theCView.ptrView;
-  if (aCView != NULL)
+  Handle(OpenGl_Window) aWindow = aView->GlWindow();
+  if (!aWindow.IsNull()
+    && aWindow->GetGlContext()->MakeCurrent())
   {
-    aCView->View->GraduatedTrihedronDisplay (aCView->WS->GetGlContext(), theCubic);
+    aCtx = aWindow->GetGlContext();
+  }
+  else
+  {
+    // try to hijack another context if any
+    const Handle(OpenGl_Context)& anOtherCtx = GetSharedContext();
+    if (!anOtherCtx.IsNull()
+      && anOtherCtx != aWindow->GetGlContext())
+    {
+      aCtx = anOtherCtx;
+      aCtx->MakeCurrent();
+    }
   }
-}
 
-// =======================================================================
-// function : GraduatedTrihedronErase
-// purpose  :
-// =======================================================================
-void OpenGl_GraphicDriver::GraduatedTrihedronErase (const Graphic3d_CView& theCView)
-{
-  const OpenGl_CView* aCView = (const OpenGl_CView* )theCView.ptrView;
-  if (aCView != NULL)
+  aView->ReleaseGlResources (aCtx);
+  if (myMapOfView.IsEmpty())
   {
-    aCView->View->GraduatedTrihedronErase (aCView->WS->GetGlContext());
+    // The last view removed but some objects still present.
+    // Release GL resources now without object destruction.
+    for (NCollection_DataMap<Standard_Integer, OpenGl_Structure*>::Iterator aStructIt (myMapOfStructure);
+         aStructIt.More (); aStructIt.Next())
+    {
+      OpenGl_Structure* aStruct = aStructIt.ChangeValue();
+      aStruct->ReleaseGlResources (aCtx);
+    }
+
+    if (!myMapOfStructure.IsEmpty())
+    {
+      aView->StructureManager()->SetDeviceLost();
+    }
   }
 }
 
 // =======================================================================
-// function : GraduatedTrihedronMinMaxValues
+// function : Window
 // purpose  :
 // =======================================================================
-void OpenGl_GraphicDriver::GraduatedTrihedronMinMaxValues (const Standard_ShortReal theMinX,
-                                                           const Standard_ShortReal theMinY,
-                                                           const Standard_ShortReal theMinZ,
-                                                           const Standard_ShortReal theMaxX,
-                                                           const Standard_ShortReal theMaxY,
-                                                           const Standard_ShortReal theMaxZ)
-{
-  OpenGl_GraduatedTrihedron::SetMinMax (theMinX, theMinY, theMinZ, theMaxX, theMaxY, theMaxZ);
+Handle(OpenGl_Window) OpenGl_GraphicDriver::CreateRenderWindow (const Handle(Aspect_Window)&  theWindow,
+                                                                const Aspect_RenderingContext theContext)
+{
+  Handle(OpenGl_Context) aShareCtx = GetSharedContext();
+  Handle(OpenGl_Window) aWindow = new OpenGl_Window (this, theWindow, theContext, myCaps, aShareCtx);
+  return aWindow;
+}
+
+//=======================================================================
+//function : ViewExists
+//purpose  :
+//=======================================================================
+Standard_Boolean OpenGl_GraphicDriver::ViewExists (const Handle(Aspect_Window)& AWindow, Handle(Graphic3d_CView)& theView)
+{
+  Standard_Boolean isExist = Standard_False;
+
+  // Parse the list of views to find
+  // a view with the specified window
+
+#if defined(_WIN32) && !defined(OCCT_UWP)
+  const Handle(WNT_Window) THEWindow = Handle(WNT_Window)::DownCast (AWindow);
+  Aspect_Handle TheSpecifiedWindowId = THEWindow->HWindow ();
+#elif defined(__APPLE__) && !defined(MACOSX_USE_GLX)
+  const Handle(Cocoa_Window) THEWindow = Handle(Cocoa_Window)::DownCast (AWindow);
+  #if defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE
+    UIView* TheSpecifiedWindowId = THEWindow->HView();
+  #else
+    NSView* TheSpecifiedWindowId = THEWindow->HView();
+  #endif
+#elif defined(__ANDROID__) || defined(__QNX__) || defined(OCCT_UWP)
+  (void )AWindow;
+  int TheSpecifiedWindowId = -1;
+#else
+  const Handle(Xw_Window) THEWindow = Handle(Xw_Window)::DownCast (AWindow);
+  int TheSpecifiedWindowId = int (THEWindow->XWindow ());
+#endif
+
+  NCollection_Map<Handle(OpenGl_View)>::Iterator aViewIt (myMapOfView);
+  for(; aViewIt.More(); aViewIt.Next())
+  {
+    const Handle(OpenGl_View)& aView = aViewIt.Value();
+    if (aView->IsDefined() && aView->IsActive())
+    {
+      const Handle(Aspect_Window) AspectWindow = aView->Window();
+
+#if defined(_WIN32) && !defined(OCCT_UWP)
+      const Handle(WNT_Window) theWindow = Handle(WNT_Window)::DownCast (AspectWindow);
+      Aspect_Handle TheWindowIdOfView = theWindow->HWindow ();
+#elif defined(__APPLE__) && !defined(MACOSX_USE_GLX)
+      const Handle(Cocoa_Window) theWindow = Handle(Cocoa_Window)::DownCast (AspectWindow);
+      #if defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE
+        UIView* TheWindowIdOfView = theWindow->HView();
+      #else
+        NSView* TheWindowIdOfView = theWindow->HView();
+      #endif
+#elif defined(__ANDROID__) || defined(__QNX__) || defined(OCCT_UWP)
+      int TheWindowIdOfView = 0;
+#else
+      const Handle(Xw_Window) theWindow = Handle(Xw_Window)::DownCast (AspectWindow);
+      int TheWindowIdOfView = int (theWindow->XWindow ());
+#endif  // WNT
+      // Comparaison on window IDs
+      if (TheWindowIdOfView == TheSpecifiedWindowId)
+      {
+        isExist = Standard_True;
+        theView = aView;
+      }
+    }
+  }
+
+  return isExist;
 }
 
-// =======================================================================
-// function : SetFlippingOptions
-// purpose  : Enable or disable flipping option for the given group
-// =======================================================================
-void OpenGl_GraphicDriver::SetFlippingOptions (const Graphic3d_CGroup& theCGroup,
-                                               const Standard_Boolean  theIsEnabled,
-                                               const gp_Ax2&           theRefPlane)
+//=======================================================================
+//function : setDeviceLost
+//purpose  :
+//=======================================================================
+void OpenGl_GraphicDriver::setDeviceLost()
 {
-  OpenGl_Flipper* aFlipper = new OpenGl_Flipper (theRefPlane);
-  aFlipper->SetOptions (theIsEnabled);
-  ((OpenGl_Group* )theCGroup.ptrGroup)->AddElement (aFlipper);
+  if (myMapOfStructure.IsEmpty())
+  {
+    return;
+  }
+
+  for (NCollection_Map<Handle(OpenGl_View)>::Iterator aViewIter (myMapOfView); aViewIter.More(); aViewIter.Next())
+  {
+    const Handle(OpenGl_View)& aView = aViewIter.Value();
+    if (aView->myWasRedrawnGL)
+    {
+      aView->StructureManager()->SetDeviceLost();
+    }
+  }
 }