0028306: Visualization - viewer crashes if style for shaded display is set to HATCH
[occt.git] / src / OpenGl / OpenGl_Context.cxx
index 77eb19c..43ae9fa 100644 (file)
 #include <OpenGl_ExtGS.hxx>
 #include <OpenGl_ArbTexBindless.hxx>
 #include <OpenGl_GlCore44.hxx>
+#include <OpenGl_FrameBuffer.hxx>
 #include <OpenGl_Sampler.hxx>
 #include <OpenGl_ShaderManager.hxx>
+#include <OpenGl_Workspace.hxx>
+#include <OpenGl_AspectFace.hxx>
+#include <Graphic3d_TransformUtils.hxx>
 
 #include <Message_Messenger.hxx>
 
@@ -35,6 +39,8 @@
 
 #include <Standard_ProgramError.hxx>
 
+IMPLEMENT_STANDARD_RTTIEXT(OpenGl_Context,Standard_Transient)
+
 #if defined(HAVE_EGL)
   #include <EGL/egl.h>
   #ifdef _MSC_VER
   //
 #elif defined(__APPLE__) && !defined(MACOSX_USE_GLX)
   #include <dlfcn.h>
+  #if defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE
+    //
+  #else
+    #include <OpenGL/OpenGL.h>
+    #include <CoreGraphics/CoreGraphics.h>
+  #endif
 #else
   #include <GL/glx.h> // glXGetProcAddress()
 #endif
 
-IMPLEMENT_STANDARD_HANDLE (OpenGl_Context, Standard_Transient)
-IMPLEMENT_STANDARD_RTTIEXT(OpenGl_Context, Standard_Transient)
+#ifdef HAVE_GL2PS
+  #include <gl2ps.h>
+  #ifdef _MSC_VER
+    #pragma comment (lib, "gl2ps.lib")
+  #endif
+#endif
+
 
 namespace
 {
   static const Handle(OpenGl_Resource) NULL_GL_RESOURCE;
+  static const OpenGl_Mat4 THE_IDENTITY_MATRIX;
+
+  //! Add key-value pair to the dictionary.
+  static void addInfo (TColStd_IndexedDataMapOfStringString& theDict,
+                       const TCollection_AsciiString& theKey,
+                       const TCollection_AsciiString& theValue)
+  {
+    theDict.ChangeFromIndex (theDict.Add (theKey, theValue)) = theValue;
+  }
+
+  //! Add key-value pair to the dictionary.
+  static void addInfo (TColStd_IndexedDataMapOfStringString& theDict,
+                       const TCollection_AsciiString& theKey,
+                       const char* theValue)
+  {
+    TCollection_AsciiString aValue (theValue != NULL ? theValue : "");
+    theDict.ChangeFromIndex (theDict.Add (theKey, aValue)) = aValue;
+  }
 }
 
 // =======================================================================
@@ -82,13 +117,16 @@ OpenGl_Context::OpenGl_Context (const Handle(OpenGl_Caps)& theCaps)
   caps   (!theCaps.IsNull() ? theCaps : new OpenGl_Caps()),
 #if defined(GL_ES_VERSION_2_0)
   hasHighp   (Standard_False),
+  hasUintIndex(Standard_False),
   hasTexRGBA8(Standard_False),
 #else
   hasHighp   (Standard_True),
+  hasUintIndex(Standard_True),
   hasTexRGBA8(Standard_True),
 #endif
   arbNPTW  (Standard_False),
   arbTexRG (Standard_False),
+  arbTexFloat (Standard_False),
   arbTexBindless (NULL),
   arbTBO (NULL),
   arbTboRGB32 (Standard_False),
@@ -96,6 +134,7 @@ OpenGl_Context::OpenGl_Context (const Handle(OpenGl_Caps)& theCaps)
   arbDbg (NULL),
   arbFBO (NULL),
   arbFBOBlit (NULL),
+  extFragDepth (Standard_False),
   extGS  (NULL),
   extBgra(Standard_False),
   extAnis(Standard_False),
@@ -112,20 +151,36 @@ OpenGl_Context::OpenGl_Context (const Handle(OpenGl_Caps)& theCaps)
   myTexClamp   (GL_CLAMP_TO_EDGE),
   myMaxTexDim  (1024),
   myMaxClipPlanes (6),
+  myMaxMsaaSamples(0),
   myGlVerMajor (0),
   myGlVerMinor (0),
   myIsInitialized (Standard_False),
   myIsStereoBuffers (Standard_False),
   myIsGlNormalizeEnabled (Standard_False),
+  myHasRayTracing (Standard_False),
+  myHasRayTracingTextures (Standard_False),
+  myHasRayTracingAdaptiveSampling (Standard_False),
 #if !defined(GL_ES_VERSION_2_0)
+  myPointSpriteOrig (GL_UPPER_LEFT),
   myRenderMode (GL_RENDER),
+  myPolygonMode (GL_FILL),
 #else
+  myPointSpriteOrig (0),
   myRenderMode (0),
+  myPolygonMode (0),
 #endif
+  myToCullBackFaces (false),
+  myReadBuffer (0),
   myDrawBuffer (0),
   myDefaultVao (0),
-  myIsGlDebugCtx (Standard_False)
+  myIsGlDebugCtx (Standard_False),
+  myResolutionRatio (1.0f)
 {
+  myViewport[0] = 0;
+  myViewport[1] = 0;
+  myViewport[2] = 0;
+  myViewport[3] = 0;
+
   // system-dependent fields
 #if defined(HAVE_EGL)
   myDisplay  = (Aspect_Display          )EGL_NO_DISPLAY;
@@ -145,13 +200,19 @@ OpenGl_Context::OpenGl_Context (const Handle(OpenGl_Caps)& theCaps)
   // Notice that GL version / extension availability checks are required
   // because function pointers may be available but not functionality itself
   // (depends on renderer).
+#if defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE
+  myGContext    = NULL;
+  myGlLibHandle = dlopen ("/System/Library/Frameworks/OpenGLES.framework/OpenGLES", RTLD_LAZY);
+#else
   myGContext    = NULL;
   myGlLibHandle = dlopen ("/System/Library/Frameworks/OpenGL.framework/Versions/Current/OpenGL", RTLD_LAZY);
+#endif
 #else
   myDisplay =  NULL;
   myWindow   = 0;
   myGContext = 0;
 #endif
+
   memset (myFuncs.operator->(), 0, sizeof(OpenGl_GlFunctions));
   myShaderManager = new OpenGl_ShaderManager (this);
 }
@@ -176,8 +237,15 @@ OpenGl_Context::~OpenGl_Context()
   myDefaultVao = 0;
 #endif
 
+  // release default FBO
+  if (!myDefaultFbo.IsNull())
+  {
+    myDefaultFbo->Release (this);
+    myDefaultFbo.Nullify();
+  }
+
   // release shared resources if any
-  if (((const Handle(Standard_Transient)& )mySharedResources)->GetRefCount() <= 1)
+  if (mySharedResources->GetRefCount() <= 1)
   {
     myShaderManager.Nullify();
     for (NCollection_DataMap<TCollection_AsciiString, Handle(OpenGl_Resource)>::Iterator anIter (*mySharedResources);
@@ -185,8 +253,15 @@ OpenGl_Context::~OpenGl_Context()
     {
       anIter.Value()->Release (this);
     }
+
+    // release delayed resources added during deletion of shared resources
+    while (!myUnusedResources->IsEmpty())
+    {
+      myUnusedResources->First()->Release (this);
+      myUnusedResources->RemoveFirst();
+    }
   }
-  else
+  else if (myShaderManager->IsSameContext (this))
   {
     myShaderManager->SetContext (NULL);
   }
@@ -199,21 +274,21 @@ OpenGl_Context::~OpenGl_Context()
     myTexSampler->Release (this);
   }
 
-#if !defined(GL_ES_VERSION_2_0)
   if (arbDbg != NULL
    && myIsGlDebugCtx
    && IsValid())
   {
     // reset callback
+  #if !defined(GL_ES_VERSION_2_0)
     void* aPtr = NULL;
-    glGetPointerv (GL_DEBUG_CALLBACK_USER_PARAM_ARB, &aPtr);
+    glGetPointerv (GL_DEBUG_CALLBACK_USER_PARAM, &aPtr);
     if (aPtr == this)
+  #endif
     {
-      arbDbg->glDebugMessageCallbackARB (NULL, NULL);
+      arbDbg->glDebugMessageCallback (NULL, NULL);
     }
     myIsGlDebugCtx = Standard_False;
   }
-#endif
 }
 
 // =======================================================================
@@ -231,123 +306,104 @@ void OpenGl_Context::forcedRelease()
   mySharedResources->Clear();
   myShaderManager->clear();
   myShaderManager->SetContext (NULL);
-}
 
-// =======================================================================
-// function : MaxDegreeOfAnisotropy
-// purpose  :
-// =======================================================================
-Standard_Integer OpenGl_Context::MaxDegreeOfAnisotropy() const
-{
-  return myAnisoMax;
+  // release delayed resources added during deletion of shared resources
+  while (!myUnusedResources->IsEmpty())
+  {
+    myUnusedResources->First()->Release (this);
+    myUnusedResources->RemoveFirst();
+  }
 }
 
 // =======================================================================
-// function : MaxTextureSize
+// function : ResizeViewport
 // purpose  :
 // =======================================================================
-Standard_Integer OpenGl_Context::MaxTextureSize() const
+void OpenGl_Context::ResizeViewport (const Standard_Integer* theRect)
 {
-  return myMaxTexDim;
+  core11fwd->glViewport (theRect[0], theRect[1], theRect[2], theRect[3]);
+  myViewport[0] = theRect[0];
+  myViewport[1] = theRect[1];
+  myViewport[2] = theRect[2];
+  myViewport[3] = theRect[3];
 }
 
-// =======================================================================
-// function : MaxClipPlanes
-// purpose  :
-// =======================================================================
-Standard_Integer OpenGl_Context::MaxClipPlanes() const
+#if !defined(GL_ES_VERSION_2_0)
+inline Standard_Integer stereoToMonoBuffer (const Standard_Integer theBuffer)
 {
-  return myMaxClipPlanes;
+  switch (theBuffer)
+  {
+    case GL_BACK_LEFT:
+    case GL_BACK_RIGHT:
+      return GL_BACK;
+    case GL_FRONT_LEFT:
+    case GL_FRONT_RIGHT:
+      return GL_FRONT;
+    default:
+      return theBuffer;
+  }
 }
+#endif
 
 // =======================================================================
-// function : SetDrawBufferLeft
+// function : SetReadBuffer
 // purpose  :
 // =======================================================================
-void OpenGl_Context::SetDrawBufferLeft()
+void OpenGl_Context::SetReadBuffer (const Standard_Integer theReadBuffer)
 {
 #if !defined(GL_ES_VERSION_2_0)
-  switch (myDrawBuffer)
+  myReadBuffer = !myIsStereoBuffers ? stereoToMonoBuffer (theReadBuffer) : theReadBuffer;
+  if (myReadBuffer < GL_COLOR_ATTACHMENT0
+   && arbFBO != NULL)
   {
-    case GL_BACK_RIGHT :
-    case GL_BACK :
-      glDrawBuffer (GL_BACK_LEFT);
-      myDrawBuffer = GL_BACK_LEFT;
-      break;
-
-    case GL_FRONT_RIGHT :
-    case GL_FRONT :
-      glDrawBuffer (GL_FRONT_LEFT);
-      myDrawBuffer = GL_FRONT_LEFT;
-      break;
-
-    case GL_FRONT_AND_BACK :
-    case GL_RIGHT :
-      glDrawBuffer (GL_LEFT);
-      myDrawBuffer = GL_LEFT;
-      break;
+    arbFBO->glBindFramebuffer (GL_FRAMEBUFFER, OpenGl_FrameBuffer::NO_FRAMEBUFFER);
   }
+  ::glReadBuffer (myReadBuffer);
+#else
+  (void )theReadBuffer;
 #endif
 }
 
 // =======================================================================
-// function : SetDrawBufferRight
+// function : SetDrawBuffer
 // purpose  :
 // =======================================================================
-void OpenGl_Context::SetDrawBufferRight()
+void OpenGl_Context::SetDrawBuffer (const Standard_Integer theDrawBuffer)
 {
 #if !defined(GL_ES_VERSION_2_0)
-  switch (myDrawBuffer)
+  myDrawBuffer = !myIsStereoBuffers ? stereoToMonoBuffer (theDrawBuffer) : theDrawBuffer;
+  if (myDrawBuffer < GL_COLOR_ATTACHMENT0
+   && arbFBO != NULL)
   {
-    case GL_BACK_LEFT :
-    case GL_BACK :
-      glDrawBuffer (GL_BACK_RIGHT);
-      myDrawBuffer = GL_BACK_RIGHT;
-      break;
-
-    case GL_FRONT_LEFT :
-    case GL_FRONT :
-      glDrawBuffer (GL_FRONT_RIGHT);
-      myDrawBuffer = GL_FRONT_RIGHT;
-      break;
-
-    case GL_FRONT_AND_BACK :
-    case GL_LEFT :
-      glDrawBuffer (GL_RIGHT);
-      myDrawBuffer = GL_RIGHT;
-      break;
+    arbFBO->glBindFramebuffer (GL_FRAMEBUFFER, OpenGl_FrameBuffer::NO_FRAMEBUFFER);
   }
+  ::glDrawBuffer (myDrawBuffer);
+#else
+  (void )theDrawBuffer;
 #endif
 }
 
 // =======================================================================
-// function : SetDrawBufferMono
+// function : SetCullBackFaces
 // purpose  :
 // =======================================================================
-void OpenGl_Context::SetDrawBufferMono()
+void OpenGl_Context::SetCullBackFaces (bool theToEnable)
 {
-#if !defined(GL_ES_VERSION_2_0)
-  switch (myDrawBuffer)
+  if (myToCullBackFaces == theToEnable)
   {
-    case GL_BACK_LEFT :
-    case GL_BACK_RIGHT :
-      glDrawBuffer (GL_BACK);
-      myDrawBuffer = GL_BACK;
-      break;
-
-    case GL_FRONT_LEFT :
-    case GL_FRONT_RIGHT :
-      glDrawBuffer (GL_FRONT);
-      myDrawBuffer = GL_FRONT;
-      break;
+    return;
+  }
 
-    case GL_LEFT :
-    case GL_RIGHT :
-      glDrawBuffer (GL_FRONT_AND_BACK);
-      myDrawBuffer = GL_FRONT_AND_BACK;
-      break;
+  myToCullBackFaces = theToEnable;
+  if (theToEnable)
+  {
+    //glCullFace (GL_BACK); GL_BACK by default
+    core11fwd->glEnable (GL_CULL_FACE);
+  }
+  else
+  {
+    core11fwd->glDisable (GL_CULL_FACE);
   }
-#endif
 }
 
 // =======================================================================
@@ -363,8 +419,9 @@ void OpenGl_Context::FetchState()
     ::glGetIntegerv (GL_RENDER_MODE, &myRenderMode);
   }
 
-  // cache draw buffer state
-  glGetIntegerv (GL_DRAW_BUFFER, &myDrawBuffer);
+  // cache buffers state
+  ::glGetIntegerv (GL_READ_BUFFER, &myReadBuffer);
+  ::glGetIntegerv (GL_DRAW_BUFFER, &myDrawBuffer);
 #endif
 }
 
@@ -439,7 +496,7 @@ Standard_Boolean OpenGl_Context::MakeCurrent()
   if (eglMakeCurrent ((EGLDisplay )myDisplay, (EGLSurface )myWindow, (EGLSurface )myWindow, (EGLContext )myGContext) != EGL_TRUE)
   {
     // if there is no current context it might be impossible to use glGetError() correctly
-    PushMessage (GL_DEBUG_SOURCE_WINDOW_SYSTEM_ARB, GL_DEBUG_TYPE_ERROR_ARB, 0, GL_DEBUG_SEVERITY_HIGH_ARB,
+    PushMessage (GL_DEBUG_SOURCE_WINDOW_SYSTEM, GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH,
                  "eglMakeCurrent() has failed!");
     myIsInitialized = Standard_False;
     return Standard_False;
@@ -471,7 +528,7 @@ Standard_Boolean OpenGl_Context::MakeCurrent()
       aMsg += (Standard_ExtString )aMsgBuff;
       LocalFree (aMsgBuff);
     }
-    PushMessage (GL_DEBUG_SOURCE_WINDOW_SYSTEM_ARB, GL_DEBUG_TYPE_ERROR_ARB, (unsigned int )anErrorCode, GL_DEBUG_SEVERITY_HIGH_ARB, aMsg);
+    PushMessage (GL_DEBUG_SOURCE_WINDOW_SYSTEM, GL_DEBUG_TYPE_ERROR, (unsigned int )anErrorCode, GL_DEBUG_SEVERITY_HIGH, aMsg);
     myIsInitialized = Standard_False;
     return Standard_False;
   }
@@ -485,7 +542,7 @@ Standard_Boolean OpenGl_Context::MakeCurrent()
   if (!glXMakeCurrent ((Display* )myDisplay, (GLXDrawable )myWindow, (GLXContext )myGContext))
   {
     // if there is no current context it might be impossible to use glGetError() correctly
-    PushMessage (GL_DEBUG_SOURCE_WINDOW_SYSTEM_ARB, GL_DEBUG_TYPE_ERROR_ARB, 0, GL_DEBUG_SEVERITY_HIGH_ARB,
+    PushMessage (GL_DEBUG_SOURCE_WINDOW_SYSTEM, GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH,
                  "glXMakeCurrent() has failed!");
     myIsInitialized = Standard_False;
     return Standard_False;
@@ -522,6 +579,48 @@ void OpenGl_Context::SwapBuffers()
 
 #endif // __APPLE__
 
+// =======================================================================
+// function : SetSwapInterval
+// purpose  :
+// =======================================================================
+Standard_Boolean OpenGl_Context::SetSwapInterval (const Standard_Integer theInterval)
+{
+#if defined(HAVE_EGL)
+  if (::eglSwapInterval ((EGLDisplay )myDisplay, theInterval) == EGL_TRUE)
+  {
+    return Standard_True;
+  }
+#elif defined(_WIN32)
+  if (myFuncs->wglSwapIntervalEXT != NULL)
+  {
+    myFuncs->wglSwapIntervalEXT (theInterval);
+    return Standard_True;
+  }
+#elif defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE
+  //
+#elif defined(__APPLE__)
+  if (::CGLSetParameter (CGLGetCurrentContext(), kCGLCPSwapInterval, &theInterval) == kCGLNoError)
+  {
+    return Standard_True;
+  }
+#else
+  if (theInterval == -1
+   && myFuncs->glXSwapIntervalEXT != NULL)
+  {
+    typedef int (*glXSwapIntervalEXT_t_x)(Display* theDisplay, GLXDrawable theDrawable, int theInterval);
+    glXSwapIntervalEXT_t_x aFuncPtr = (glXSwapIntervalEXT_t_x )myFuncs->glXSwapIntervalEXT;
+    aFuncPtr ((Display* )myDisplay, (GLXDrawable )myWindow, theInterval);
+    return Standard_True;
+  }
+  else if (myFuncs->glXSwapIntervalSGI != NULL)
+  {
+    myFuncs->glXSwapIntervalSGI (theInterval);
+    return Standard_True;
+  }
+#endif
+  return Standard_False;
+}
+
 // =======================================================================
 // function : findProc
 // purpose  :
@@ -531,7 +630,7 @@ void* OpenGl_Context::findProc (const char* theFuncName)
 #if defined(HAVE_EGL)
   return (void* )eglGetProcAddress (theFuncName);
 #elif defined(_WIN32)
-  return wglGetProcAddress (theFuncName);
+  return (void* )wglGetProcAddress (theFuncName);
 #elif defined(__APPLE__) && !defined(MACOSX_USE_GLX)
   return (myGlLibHandle != NULL) ? dlsym (myGlLibHandle, theFuncName) : NULL;
 #else
@@ -667,8 +766,15 @@ Standard_Boolean OpenGl_Context::Init (const Aspect_Handle           theWindow,
                                        const Aspect_RenderingContext theGContext,
                                        const Standard_Boolean        theIsCoreProfile)
 #elif defined(__APPLE__) && !defined(MACOSX_USE_GLX)
-Standard_Boolean OpenGl_Context::Init (const void*                   theGContext,
+
+#if defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE
+Standard_Boolean OpenGl_Context::Init (EAGLContext*                  theGContext,
+                                       const Standard_Boolean        theIsCoreProfile)
+#else
+Standard_Boolean OpenGl_Context::Init (NSOpenGLContext*              theGContext,
                                        const Standard_Boolean        theIsCoreProfile)
+#endif
+
 #else
 Standard_Boolean OpenGl_Context::Init (const Aspect_Drawable         theWindow,
                                        const Aspect_Display          theDisplay,
@@ -686,7 +792,7 @@ Standard_Boolean OpenGl_Context::Init (const Aspect_Drawable         theWindow,
   myGContext = theGContext;
   myWindowDC = theWindowDC;
 #elif defined(__APPLE__) && !defined(MACOSX_USE_GLX)
-  myGContext = (void* )theGContext;
+  myGContext = theGContext;
 #else
   myWindow   = theWindow;
   myGContext = theGContext;
@@ -706,12 +812,45 @@ Standard_Boolean OpenGl_Context::Init (const Aspect_Drawable         theWindow,
 // function : ResetErrors
 // purpose  :
 // =======================================================================
-void OpenGl_Context::ResetErrors()
+bool OpenGl_Context::ResetErrors (const bool theToPrintErrors)
 {
-  while (glGetError() != GL_NO_ERROR)
+  int aPrevErr = 0;
+  int anErr    = ::glGetError();
+  const bool hasError = anErr != GL_NO_ERROR;
+  if (!theToPrintErrors)
   {
-    //
+    for (; anErr != GL_NO_ERROR && aPrevErr != anErr; aPrevErr = anErr, anErr = ::glGetError())
+    {
+      //
+    }
+    return hasError;
+  }
+
+  for (; anErr != GL_NO_ERROR && aPrevErr != anErr; aPrevErr = anErr, anErr = ::glGetError())
+  {
+    TCollection_ExtendedString anErrId;
+    switch (anErr)
+    {
+      case GL_INVALID_ENUM:      anErrId = "GL_INVALID_ENUM";      break;
+      case GL_INVALID_VALUE:     anErrId = "GL_INVALID_VALUE";     break;
+      case GL_INVALID_OPERATION: anErrId = "GL_INVALID_OPERATION"; break;
+    #ifdef GL_STACK_OVERFLOW
+      case GL_STACK_OVERFLOW:    anErrId = "GL_STACK_OVERFLOW";    break;
+      case GL_STACK_UNDERFLOW:   anErrId = "GL_STACK_UNDERFLOW";   break;
+    #endif
+      case GL_OUT_OF_MEMORY:     anErrId = "GL_OUT_OF_MEMORY";     break;
+      case GL_INVALID_FRAMEBUFFER_OPERATION:
+        anErrId = "GL_INVALID_FRAMEBUFFER_OPERATION";
+        break;
+      default:
+        anErrId = TCollection_ExtendedString("#") + anErr;
+        break;
+    }
+
+    const TCollection_ExtendedString aMsg = TCollection_ExtendedString ("Unhandled GL error: ") + anErrId;
+    PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_OTHER, 0, GL_DEBUG_SEVERITY_LOW, aMsg);
   }
+  return hasError;
 }
 
 // =======================================================================
@@ -817,29 +956,28 @@ void OpenGl_Context::ReadGlVersion (Standard_Integer& theGlVerMajor,
 static Standard_CString THE_DBGMSG_UNKNOWN = "UNKNOWN";
 static Standard_CString THE_DBGMSG_SOURCES[] =
 {
-  ".OpenGL",    // GL_DEBUG_SOURCE_API_ARB
-  ".WinSystem", // GL_DEBUG_SOURCE_WINDOW_SYSTEM_ARB
-  ".GLSL",      // GL_DEBUG_SOURCE_SHADER_COMPILER_ARB
-  ".3rdParty",  // GL_DEBUG_SOURCE_THIRD_PARTY_ARB
-  "",           // GL_DEBUG_SOURCE_APPLICATION_ARB
-  ".Other"      // GL_DEBUG_SOURCE_OTHER_ARB
+  ".OpenGL",    // GL_DEBUG_SOURCE_API
+  ".WinSystem", // GL_DEBUG_SOURCE_WINDOW_SYSTEM
+  ".GLSL",      // GL_DEBUG_SOURCE_SHADER_COMPILER
+  ".3rdParty",  // GL_DEBUG_SOURCE_THIRD_PARTY
+  "",           // GL_DEBUG_SOURCE_APPLICATION
+  ".Other"      // GL_DEBUG_SOURCE_OTHER
 };
 
 static Standard_CString THE_DBGMSG_TYPES[] =
 {
-  "Error",           // GL_DEBUG_TYPE_ERROR_ARB
-  "Deprecated",      // GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR_ARB
-  "Undef. behavior", // GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR_ARB
-  "Portability",     // GL_DEBUG_TYPE_PORTABILITY_ARB
-  "Performance",     // GL_DEBUG_TYPE_PERFORMANCE_ARB
-  "Other"            // GL_DEBUG_TYPE_OTHER_ARB
+  "Error",           // GL_DEBUG_TYPE_ERROR
+  "Deprecated",      // GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR
+  "Undef. behavior", // GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR
+  "Portability",     // GL_DEBUG_TYPE_PORTABILITY
+  "Performance",     // GL_DEBUG_TYPE_PERFORMANCE
+  "Other"            // GL_DEBUG_TYPE_OTHER
 };
 
-static Standard_CString THE_DBGMSG_SEV_HIGH   = "High";   // GL_DEBUG_SEVERITY_HIGH_ARB
-static Standard_CString THE_DBGMSG_SEV_MEDIUM = "Medium"; // GL_DEBUG_SEVERITY_MEDIUM_ARB
-static Standard_CString THE_DBGMSG_SEV_LOW    = "Low";    // GL_DEBUG_SEVERITY_LOW_ARB
+static Standard_CString THE_DBGMSG_SEV_HIGH   = "High";   // GL_DEBUG_SEVERITY_HIGH
+static Standard_CString THE_DBGMSG_SEV_MEDIUM = "Medium"; // GL_DEBUG_SEVERITY_MEDIUM
+static Standard_CString THE_DBGMSG_SEV_LOW    = "Low";    // GL_DEBUG_SEVERITY_LOW
 
-#if !defined(GL_ES_VERSION_2_0)
 //! Callback for GL_ARB_debug_output extension
 static void APIENTRY debugCallbackWrap(unsigned int theSource,
                                        unsigned int theType,
@@ -852,7 +990,6 @@ static void APIENTRY debugCallbackWrap(unsigned int theSource,
   OpenGl_Context* aCtx = (OpenGl_Context* )theUserParam;
   aCtx->PushMessage (theSource, theType, theId, theSeverity, theMessage);
 }
-#endif
 
 // =======================================================================
 // function : PushMessage
@@ -864,23 +1001,30 @@ void OpenGl_Context::PushMessage (const unsigned int theSource,
                                   const unsigned int theSeverity,
                                   const TCollection_ExtendedString& theMessage)
 {
-  //OpenGl_Context* aCtx = (OpenGl_Context* )theUserParam;
-  Standard_CString& aSrc = (theSource >= GL_DEBUG_SOURCE_API_ARB
-                        && theSource <= GL_DEBUG_SOURCE_OTHER_ARB)
-                         ? THE_DBGMSG_SOURCES[theSource - GL_DEBUG_SOURCE_API_ARB]
+  if (caps->suppressExtraMsg
+   && theSource >= GL_DEBUG_SOURCE_API
+   && theSource <= GL_DEBUG_SOURCE_OTHER
+   && myFilters[theSource - GL_DEBUG_SOURCE_API].Contains (theId))
+  {
+    return;
+  }
+
+  Standard_CString& aSrc = (theSource >= GL_DEBUG_SOURCE_API
+                        && theSource <= GL_DEBUG_SOURCE_OTHER)
+                         ? THE_DBGMSG_SOURCES[theSource - GL_DEBUG_SOURCE_API]
                          : THE_DBGMSG_UNKNOWN;
-  Standard_CString& aType = (theType >= GL_DEBUG_TYPE_ERROR_ARB
-                         && theType <= GL_DEBUG_TYPE_OTHER_ARB)
-                          ? THE_DBGMSG_TYPES[theType - GL_DEBUG_TYPE_ERROR_ARB]
+  Standard_CString& aType = (theType >= GL_DEBUG_TYPE_ERROR
+                         && theType <= GL_DEBUG_TYPE_OTHER)
+                          ? THE_DBGMSG_TYPES[theType - GL_DEBUG_TYPE_ERROR]
                           : THE_DBGMSG_UNKNOWN;
-  Standard_CString& aSev = theSeverity == GL_DEBUG_SEVERITY_HIGH_ARB
+  Standard_CString& aSev = theSeverity == GL_DEBUG_SEVERITY_HIGH
                          ? THE_DBGMSG_SEV_HIGH
-                         : (theSeverity == GL_DEBUG_SEVERITY_MEDIUM_ARB
+                         : (theSeverity == GL_DEBUG_SEVERITY_MEDIUM
                           ? THE_DBGMSG_SEV_MEDIUM
                           : THE_DBGMSG_SEV_LOW);
-  Message_Gravity aGrav = theSeverity == GL_DEBUG_SEVERITY_HIGH_ARB
+  Message_Gravity aGrav = theSeverity == GL_DEBUG_SEVERITY_HIGH
                         ? Message_Alarm
-                        : (theSeverity == GL_DEBUG_SEVERITY_MEDIUM_ARB
+                        : (theSeverity == GL_DEBUG_SEVERITY_MEDIUM
                          ? Message_Warning
                          : Message_Info);
 
@@ -894,6 +1038,54 @@ void OpenGl_Context::PushMessage (const unsigned int theSource,
   Messenger()->Send (aMsg, aGrav);
 }
 
+// =======================================================================
+// function : ExcludeMessage
+// purpose  :
+// ======================================================================
+Standard_Boolean OpenGl_Context::ExcludeMessage (const unsigned int theSource,
+                                                 const unsigned int theId)
+{
+  return theSource >= GL_DEBUG_SOURCE_API
+      && theSource <= GL_DEBUG_SOURCE_OTHER
+      && myFilters[theSource - GL_DEBUG_SOURCE_API].Add (theId);
+}
+
+// =======================================================================
+// function : IncludeMessage
+// purpose  :
+// ======================================================================
+Standard_Boolean OpenGl_Context::IncludeMessage (const unsigned int theSource,
+                                                 const unsigned int theId)
+{
+  return theSource >= GL_DEBUG_SOURCE_API
+      && theSource <= GL_DEBUG_SOURCE_OTHER
+      && myFilters[theSource - GL_DEBUG_SOURCE_API].Remove (theId);
+}
+
+// =======================================================================
+// function : checkWrongVersion
+// purpose  :
+// ======================================================================
+void OpenGl_Context::checkWrongVersion (const Standard_Integer theGlVerMajor,
+                                        const Standard_Integer theGlVerMinor)
+{
+  if (!IsGlGreaterEqual (theGlVerMajor, theGlVerMinor))
+  {
+    return;
+  }
+
+  TCollection_ExtendedString aMsg = TCollection_ExtendedString()
+    + "Error! OpenGL context reports version "
+    + myGlVerMajor  + "." + myGlVerMinor
+    + " but does not export required functions for "
+    + theGlVerMajor + "." + theGlVerMinor;
+  PushMessage (GL_DEBUG_SOURCE_APPLICATION,
+               GL_DEBUG_TYPE_ERROR,
+               0,
+               GL_DEBUG_SEVERITY_HIGH,
+               aMsg);
+}
+
 // =======================================================================
 // function : init
 // purpose  :
@@ -903,38 +1095,54 @@ void OpenGl_Context::init (const Standard_Boolean theIsCoreProfile)
   // read version
   myGlVerMajor = 0;
   myGlVerMinor = 0;
+  myMaxMsaaSamples = 0;
   ReadGlVersion (myGlVerMajor, myGlVerMinor);
+  myVendor = (const char* )::glGetString (GL_VENDOR);
+  if (!caps->ffpEnable
+   && !IsGlGreaterEqual (2, 0))
+  {
+    caps->ffpEnable = true;
+    TCollection_ExtendedString aMsg =
+      TCollection_ExtendedString("OpenGL driver is too old! Context info:\n")
+                               + "    Vendor:   " + (const char* )::glGetString (GL_VENDOR)   + "\n"
+                               + "    Renderer: " + (const char* )::glGetString (GL_RENDERER) + "\n"
+                               + "    Version:  " + (const char* )::glGetString (GL_VERSION)  + "\n"
+                               + "  Fallback using deprecated fixed-function pipeline.\n"
+                               + "  Visualization might work incorrectly.\n"
+                                 "  Consider upgrading the graphics driver.";
+    PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_PORTABILITY, 0, GL_DEBUG_SEVERITY_HIGH, aMsg);
+  }
 
 #if defined(GL_ES_VERSION_2_0)
   (void )theIsCoreProfile;
   const bool isCoreProfile = false;
 #else
+
+  if (myVendor.Search ("NVIDIA") != -1)
+  {
+    // Buffer detailed info: Buffer object 1 (bound to GL_ARRAY_BUFFER_ARB, usage hint is GL_STATIC_DRAW)
+    // will use VIDEO memory as the source for buffer object operations.
+    ExcludeMessage (GL_DEBUG_SOURCE_API, 131185);
+  }
   if (IsGlGreaterEqual (3, 0))
   {
     // retrieve auxiliary function in advance
     FindProc ("glGetStringi", myFuncs->glGetStringi);
   }
 
-  // this check would not work well due to buggy NVIDIA drivers!
-  /*GLint aProfile = 0;
+  bool isCoreProfile = false;
   if (IsGlGreaterEqual (3, 2))
   {
-    ::glGetIntegerv (GL_CONTEXT_PROFILE_MASK, &aProfile);
-  }
-  const bool isCoreProfile = (aProfile & GL_CONTEXT_CORE_PROFILE_BIT) != 0;*/
+    isCoreProfile = (theIsCoreProfile == Standard_True);
 
-  // detect Core profile
-  /*for (int anErr = glGetError(), aPrevErr = GL_NO_ERROR;; aPrevErr = anErr, anErr = glGetError())
-  {
-    if (anErr == aPrevErr)
+    // detect Core profile
+    if (!isCoreProfile)
     {
-      break;
+      GLint aProfile = 0;
+      ::glGetIntegerv (GL_CONTEXT_PROFILE_MASK, &aProfile);
+      isCoreProfile = (aProfile & GL_CONTEXT_CORE_PROFILE_BIT) != 0;
     }
   }
-  const char* anExtString = (const char* )::glGetString (GL_EXTENSIONS);
-  const bool isCoreProfile = IsGlGreaterEqual (3, 2) && (glGetError() != GL_NO_ERROR);*/
-
-  const bool isCoreProfile = IsGlGreaterEqual (3, 2) && theIsCoreProfile;
 #endif
 
   core11     = NULL;
@@ -998,26 +1206,81 @@ void OpenGl_Context::init (const Standard_Boolean theIsCoreProfile)
   {
     arbFBOBlit = (OpenGl_ArbFBOBlit* )(&(*myFuncs));
   }
+  extFragDepth = !IsGlGreaterEqual(3, 0)
+               && CheckExtension ("GL_EXT_frag_depth");
+  if (IsGlGreaterEqual (3, 1)
+   && FindProc ("glTexStorage2DMultisample", myFuncs->glTexStorage2DMultisample))
+  {
+    // MSAA RenderBuffers have been defined in OpenGL ES 3.0,
+    // but MSAA Textures - only in OpenGL ES 3.1+
+    ::glGetIntegerv (GL_MAX_SAMPLES, &myMaxMsaaSamples);
+  }
 
-  hasHighp = CheckExtension ("OES_fragment_precision_high");
+  hasUintIndex = IsGlGreaterEqual (3, 0)
+              || CheckExtension ("GL_OES_element_index_uint");
+  hasHighp     = CheckExtension ("GL_OES_fragment_precision_high");
   GLint aRange[2] = {0, 0};
-  GLint aPrec [2] = {0, 0};
-  ::glGetShaderPrecisionFormat (GL_FRAGMENT_SHADER, GL_HIGH_FLOAT, aRange, aPrec);
-  if (aPrec[1] != 0)
+  GLint aPrec     = 0;
+  ::glGetShaderPrecisionFormat (GL_FRAGMENT_SHADER, GL_HIGH_FLOAT, aRange, &aPrec);
+  if (aPrec != 0)
   {
     hasHighp = Standard_True;
   }
+
+  arbTexFloat = IsGlGreaterEqual (3, 0)
+             && FindProc ("glTexImage3D", myFuncs->glTexImage3D);
+
+  const Standard_Boolean hasTexBuffer32  = IsGlGreaterEqual (3, 2) && FindProc ("glTexBuffer", myFuncs->glTexBuffer);
+  const Standard_Boolean hasExtTexBuffer = CheckExtension ("GL_EXT_texture_buffer") && FindProc ("glTexBufferEXT", myFuncs->glTexBuffer);
+
+  if (hasTexBuffer32 || hasExtTexBuffer)
+  {
+    arbTBO = reinterpret_cast<OpenGl_ArbTBO*> (myFuncs.get());
+  }
+
+  // initialize debug context extension
+  if (CheckExtension ("GL_KHR_debug"))
+  {
+    // this functionality become a part of OpenGL ES 3.2
+    arbDbg = NULL;
+    // According to GL_KHR_debug spec, all functions should have KHR suffix.
+    // However, some implementations can export these functions without suffix.
+    if (FindProc ("glDebugMessageControlKHR",  myFuncs->glDebugMessageControl)
+     && FindProc ("glDebugMessageInsertKHR",   myFuncs->glDebugMessageInsert)
+     && FindProc ("glDebugMessageCallbackKHR", myFuncs->glDebugMessageCallback)
+     && FindProc ("glGetDebugMessageLogKHR",   myFuncs->glGetDebugMessageLog))
+    {
+      arbDbg = (OpenGl_ArbDbg* )(&(*myFuncs));
+    }
+
+    if (arbDbg != NULL
+     && caps->contextDebug)
+    {
+      // setup default callback
+      myIsGlDebugCtx = Standard_True;
+      arbDbg->glDebugMessageCallback (debugCallbackWrap, this);
+      ::glEnable (GL_DEBUG_OUTPUT);
+      if (caps->contextSyncDebug)
+      {
+        // note that some broken implementations (e.g. simulators) might generate error message on this call
+        ::glEnable (GL_DEBUG_OUTPUT_SYNCHRONOUS);
+      }
+    }
+  }
+
 #else
 
   myTexClamp = IsGlGreaterEqual (1, 2) ? GL_CLAMP_TO_EDGE : GL_CLAMP;
 
   hasTexRGBA8 = Standard_True;
-  arbNPTW = CheckExtension ("GL_ARB_texture_non_power_of_two");
-  extBgra = CheckExtension ("GL_EXT_bgra");
-  extAnis = CheckExtension ("GL_EXT_texture_filter_anisotropic");
-  extPDS  = CheckExtension ("GL_EXT_packed_depth_stencil");
-  atiMem  = CheckExtension ("GL_ATI_meminfo");
-  nvxMem  = CheckExtension ("GL_NVX_gpu_memory_info");
+  arbNPTW     = CheckExtension ("GL_ARB_texture_non_power_of_two");
+  arbTexFloat = IsGlGreaterEqual (3, 0)
+             || CheckExtension ("GL_ARB_texture_float");
+  extBgra     = CheckExtension ("GL_EXT_bgra");
+  extAnis     = CheckExtension ("GL_EXT_texture_filter_anisotropic");
+  extPDS      = CheckExtension ("GL_EXT_packed_depth_stencil");
+  atiMem      = CheckExtension ("GL_ATI_meminfo");
+  nvxMem      = CheckExtension ("GL_NVX_gpu_memory_info");
 
   GLint aStereo = GL_FALSE;
   glGetIntegerv (GL_STEREO, &aStereo);
@@ -1058,7 +1321,9 @@ void OpenGl_Context::init (const Standard_Boolean theIsCoreProfile)
   #define FindProcShort(theFunc) FindProc(#theFunc, myFuncs->theFunc)
 
   // retrieve platform-dependent extensions
-#if defined(_WIN32) && !defined(HAVE_EGL)
+#if defined(HAVE_EGL)
+  //
+#elif defined(_WIN32)
   if (FindProcShort (wglGetExtensionsStringARB))
   {
     const char* aWglExts = myFuncs->wglGetExtensionsStringARB (wglGetCurrentDC());
@@ -1086,30 +1351,27 @@ void OpenGl_Context::init (const Standard_Boolean theIsCoreProfile)
       FindProcShort (wglDXUnlockObjectsNV);
     }
   }
-#endif
-
-  // initialize debug context extension
-  if (CheckExtension ("GL_ARB_debug_output"))
-  {
-    arbDbg = NULL;
-    if (FindProcShort (glDebugMessageControlARB)
-     && FindProcShort (glDebugMessageInsertARB)
-     && FindProcShort (glDebugMessageCallbackARB)
-     && FindProcShort (glGetDebugMessageLogARB))
+#elif defined(__APPLE__)
+    //
+#else
+    const char* aGlxExts = ::glXQueryExtensionsString ((Display* )myDisplay, DefaultScreen ((Display* )myDisplay));
+    if (CheckExtension (aGlxExts, "GLX_EXT_swap_control"))
     {
-      arbDbg = (OpenGl_ArbDbg* )(&(*myFuncs));
+      FindProcShort (glXSwapIntervalEXT);
     }
-    if (arbDbg != NULL
-     && caps->contextDebug)
+    if (CheckExtension (aGlxExts, "GLX_SGI_swap_control"))
     {
-      // setup default callback
-      myIsGlDebugCtx = Standard_True;
-      arbDbg->glDebugMessageCallbackARB (debugCallbackWrap, this);
-    #ifdef OCCT_DEBUG
-      glEnable (GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB);
-    #endif
+      FindProcShort (glXSwapIntervalSGI);
     }
-  }
+    if (CheckExtension (aGlxExts, "GLX_MESA_query_renderer"))
+    {
+      FindProcShort (glXQueryRendererIntegerMESA);
+      FindProcShort (glXQueryCurrentRendererIntegerMESA);
+      FindProcShort (glXQueryRendererStringMESA);
+      FindProcShort (glXQueryCurrentRendererStringMESA);
+    }
+    //extSwapTear = CheckExtension (aGlxExts, "GLX_EXT_swap_control_tear");
+#endif
 
   // load OpenGL 1.2 new functions
   has12 = IsGlGreaterEqual (1, 2)
@@ -1509,7 +1771,21 @@ void OpenGl_Context::init (const Standard_Boolean theIsCoreProfile)
 
   // load GL_ARB_vertex_type_2_10_10_10_rev (added to OpenGL 3.3 core)
   const bool hasVertType21010101rev = (IsGlGreaterEqual (3, 3) || CheckExtension ("GL_ARB_vertex_type_2_10_10_10_rev"))
-       && FindProcShort (glVertexP2ui)
+       && FindProcShort (glVertexAttribP1ui)
+       && FindProcShort (glVertexAttribP1uiv)
+       && FindProcShort (glVertexAttribP2ui)
+       && FindProcShort (glVertexAttribP2uiv)
+       && FindProcShort (glVertexAttribP3ui)
+       && FindProcShort (glVertexAttribP3uiv)
+       && FindProcShort (glVertexAttribP4ui)
+       && FindProcShort (glVertexAttribP4uiv);
+
+  if ( hasVertType21010101rev
+   && !isCoreProfile)
+  {
+    // load deprecated functions
+    const bool hasVertType21010101revExt =
+          FindProcShort (glVertexP2ui)
        && FindProcShort (glVertexP2uiv)
        && FindProcShort (glVertexP3ui)
        && FindProcShort (glVertexP3uiv)
@@ -1538,15 +1814,9 @@ void OpenGl_Context::init (const Standard_Boolean theIsCoreProfile)
        && FindProcShort (glColorP4ui)
        && FindProcShort (glColorP4uiv)
        && FindProcShort (glSecondaryColorP3ui)
-       && FindProcShort (glSecondaryColorP3uiv)
-       && FindProcShort (glVertexAttribP1ui)
-       && FindProcShort (glVertexAttribP1uiv)
-       && FindProcShort (glVertexAttribP2ui)
-       && FindProcShort (glVertexAttribP2uiv)
-       && FindProcShort (glVertexAttribP3ui)
-       && FindProcShort (glVertexAttribP3uiv)
-       && FindProcShort (glVertexAttribP4ui)
-       && FindProcShort (glVertexAttribP4uiv);
+       && FindProcShort (glSecondaryColorP3uiv);
+    (void )hasVertType21010101revExt;
+  }
 
   // load OpenGL 3.3 extra functions
   has33 = IsGlGreaterEqual (3, 3)
@@ -1768,10 +2038,7 @@ void OpenGl_Context::init (const Standard_Boolean theIsCoreProfile)
   const bool hasTextureStorage = (IsGlGreaterEqual (4, 2) || CheckExtension ("GL_ARB_texture_storage"))
        && FindProcShort (glTexStorage1D)
        && FindProcShort (glTexStorage2D)
-       && FindProcShort (glTexStorage3D)
-       && FindProcShort (glTextureStorage1DEXT)
-       && FindProcShort (glTextureStorage2DEXT)
-       && FindProcShort (glTextureStorage3DEXT);
+       && FindProcShort (glTexStorage3D);
 
   has42 = IsGlGreaterEqual (4, 2)
        && hasBaseInstance
@@ -1841,6 +2108,39 @@ void OpenGl_Context::init (const Standard_Boolean theIsCoreProfile)
        && FindProcShort (glBindImageTextures)
        && FindProcShort (glBindVertexBuffers);
 
+  // initialize debug context extension
+  if (CheckExtension ("GL_ARB_debug_output"))
+  {
+    arbDbg = NULL;
+    if (has43)
+    {
+      arbDbg = (OpenGl_ArbDbg* )(&(*myFuncs));
+    }
+    else if (FindProc ("glDebugMessageControlARB",  myFuncs->glDebugMessageControl)
+          && FindProc ("glDebugMessageInsertARB",   myFuncs->glDebugMessageInsert)
+          && FindProc ("glDebugMessageCallbackARB", myFuncs->glDebugMessageCallback)
+          && FindProc ("glGetDebugMessageLogARB",   myFuncs->glGetDebugMessageLog))
+    {
+      arbDbg = (OpenGl_ArbDbg* )(&(*myFuncs));
+    }
+
+    if (arbDbg != NULL
+     && caps->contextDebug)
+    {
+      // setup default callback
+      myIsGlDebugCtx = Standard_True;
+      arbDbg->glDebugMessageCallback (debugCallbackWrap, this);
+      if (has43)
+      {
+        ::glEnable (GL_DEBUG_OUTPUT);
+      }
+      if (caps->contextSyncDebug)
+      {
+        ::glEnable (GL_DEBUG_OUTPUT_SYNCHRONOUS);
+      }
+    }
+  }
+
   // initialize TBO extension (ARB)
   if (!has31
    && CheckExtension ("GL_ARB_texture_buffer_object")
@@ -1898,24 +2198,28 @@ void OpenGl_Context::init (const Standard_Boolean theIsCoreProfile)
 
   if (!has12)
   {
+    checkWrongVersion (1, 2);
     myGlVerMajor = 1;
     myGlVerMinor = 1;
     return;
   }
   else if (!has13)
   {
+    checkWrongVersion (1, 3);
     myGlVerMajor = 1;
     myGlVerMinor = 2;
     return;
   }
   else if (!has14)
   {
+    checkWrongVersion (1, 4);
     myGlVerMajor = 1;
     myGlVerMinor = 3;
     return;
   }
   else if (!has15)
   {
+    checkWrongVersion (1, 5);
     myGlVerMajor = 1;
     myGlVerMinor = 4;
     return;
@@ -1928,6 +2232,26 @@ void OpenGl_Context::init (const Standard_Boolean theIsCoreProfile)
 
   if (!has20)
   {
+    checkWrongVersion (2, 0);
+    myGlVerMajor = 1;
+    myGlVerMinor = 5;
+    return;
+  }
+
+  const char* aGlslVer = (const char* )::glGetString (GL_SHADING_LANGUAGE_VERSION);
+  if (aGlslVer == NULL
+  || *aGlslVer == '\0')
+  {
+    // broken context has been detected
+    TCollection_ExtendedString aMsg = TCollection_ExtendedString()
+      + "Error! OpenGL context reports version "
+      + myGlVerMajor  + "." + myGlVerMinor
+      + " but reports wrong GLSL version";
+    PushMessage (GL_DEBUG_SOURCE_APPLICATION,
+                 GL_DEBUG_TYPE_ERROR,
+                 0,
+                 GL_DEBUG_SEVERITY_HIGH,
+                 aMsg);
     myGlVerMajor = 1;
     myGlVerMinor = 5;
     return;
@@ -1941,6 +2265,7 @@ void OpenGl_Context::init (const Standard_Boolean theIsCoreProfile)
 
   if (!has21)
   {
+    checkWrongVersion (2, 1);
     myGlVerMajor = 2;
     myGlVerMinor = 0;
     return;
@@ -1948,13 +2273,33 @@ void OpenGl_Context::init (const Standard_Boolean theIsCoreProfile)
 
   if (!has30)
   {
+    checkWrongVersion (3, 0);
     myGlVerMajor = 2;
     myGlVerMinor = 1;
     return;
   }
 
+  // MSAA RenderBuffers have been defined in OpenGL 3.0,
+  // but MSAA Textures - only in OpenGL 3.2+
+  if (!has32
+   && CheckExtension ("GL_ARB_texture_multisample")
+   && FindProcShort (glTexImage2DMultisample))
+  {
+    GLint aNbColorSamples = 0, aNbDepthSamples = 0;
+    ::glGetIntegerv (GL_MAX_COLOR_TEXTURE_SAMPLES, &aNbColorSamples);
+    ::glGetIntegerv (GL_MAX_DEPTH_TEXTURE_SAMPLES, &aNbDepthSamples);
+    myMaxMsaaSamples = Min (aNbColorSamples, aNbDepthSamples);
+  }
+  if (!has43
+   && CheckExtension ("GL_ARB_texture_storage_multisample")
+   && FindProcShort (glTexStorage2DMultisample))
+  {
+    //
+  }
+
   if (!has31)
   {
+    checkWrongVersion (3, 1);
     myGlVerMajor = 3;
     myGlVerMinor = 0;
     return;
@@ -1962,8 +2307,23 @@ void OpenGl_Context::init (const Standard_Boolean theIsCoreProfile)
   arbTBO = (OpenGl_ArbTBO* )(&(*myFuncs));
   arbIns = (OpenGl_ArbIns* )(&(*myFuncs));
 
+  // check whether ray tracing mode is supported
+  myHasRayTracing = has31
+                 && arbTboRGB32
+                 && arbFBOBlit  != NULL;
+
+  // check whether textures in ray tracing mode are supported
+  myHasRayTracingTextures = myHasRayTracing
+                         && arbTexBindless != NULL;
+
+  // check whether adaptive screen sampling in ray tracing mode is supported
+  myHasRayTracingAdaptiveSampling = myHasRayTracing
+                                 && has44
+                                 && CheckExtension ("GL_NV_shader_atomic_float");
+
   if (!has32)
   {
+    checkWrongVersion (3, 2);
     myGlVerMajor = 3;
     myGlVerMinor = 1;
     return;
@@ -1977,9 +2337,11 @@ void OpenGl_Context::init (const Standard_Boolean theIsCoreProfile)
   {
     core32back = (OpenGl_GlCore32Back* )(&(*myFuncs));
   }
+  ::glGetIntegerv (GL_MAX_SAMPLES, &myMaxMsaaSamples);
 
   if (!has33)
   {
+    checkWrongVersion (3, 3);
     myGlVerMajor = 3;
     myGlVerMinor = 2;
     return;
@@ -1996,6 +2358,7 @@ void OpenGl_Context::init (const Standard_Boolean theIsCoreProfile)
 
   if (!has40)
   {
+    checkWrongVersion (4, 0);
     myGlVerMajor = 3;
     myGlVerMinor = 3;
     return;
@@ -2004,6 +2367,7 @@ void OpenGl_Context::init (const Standard_Boolean theIsCoreProfile)
 
   if (!has41)
   {
+    checkWrongVersion (4, 1);
     myGlVerMajor = 4;
     myGlVerMinor = 0;
     return;
@@ -2016,6 +2380,7 @@ void OpenGl_Context::init (const Standard_Boolean theIsCoreProfile)
 
   if(!has42)
   {
+    checkWrongVersion (4, 2);
     myGlVerMajor = 4;
     myGlVerMinor = 1;
     return;
@@ -2028,6 +2393,7 @@ void OpenGl_Context::init (const Standard_Boolean theIsCoreProfile)
 
   if (!has43)
   {
+    checkWrongVersion (4, 3);
     myGlVerMajor = 4;
     myGlVerMinor = 2;
     return;
@@ -2040,6 +2406,7 @@ void OpenGl_Context::init (const Standard_Boolean theIsCoreProfile)
 
   if (!has44)
   {
+    checkWrongVersion (4, 4);
     myGlVerMajor = 4;
     myGlVerMinor = 3;
     return;
@@ -2087,23 +2454,90 @@ Standard_Size OpenGl_Context::AvailableMemory() const
 // =======================================================================
 TCollection_AsciiString OpenGl_Context::MemoryInfo() const
 {
-  TCollection_AsciiString anInfo;
-#if !defined(GL_ES_VERSION_2_0)
-  if (atiMem)
-  {
-    GLint aValues[4];
-    memset (aValues, 0, sizeof(aValues));
-    glGetIntegerv (GL_VBO_FREE_MEMORY_ATI, aValues);
+  TColStd_IndexedDataMapOfStringString aDict;
+  MemoryInfo (aDict);
 
-    // total memory free in the pool
-    anInfo += TCollection_AsciiString ("  GPU free memory:    ") + (aValues[0] / 1024) + " MiB\n";
+  TCollection_AsciiString aText;
+  for (TColStd_IndexedDataMapOfStringString::Iterator anIter (aDict); anIter.More(); anIter.Next())
+  {
+    if (!aText.IsEmpty())
+    {
+      aText += "\n";
+    }
+    aText += TCollection_AsciiString("  ") + anIter.Key() + ": " + anIter.Value();
+  }
+  return aText;
+}
 
-    // largest available free block in the pool
-    anInfo += TCollection_AsciiString ("  Largest free block: ") + (aValues[1] / 1024) + " MiB\n";
+// =======================================================================
+// function : MemoryInfo
+// purpose  :
+// =======================================================================
+void OpenGl_Context::MemoryInfo (TColStd_IndexedDataMapOfStringString& theDict) const
+{
+#if defined(GL_ES_VERSION_2_0)
+  (void )theDict;
+#elif defined(__APPLE__) && !defined(MACOSX_USE_GLX)
+  GLint aGlRendId = 0;
+  CGLGetParameter (CGLGetCurrentContext(), kCGLCPCurrentRendererID, &aGlRendId);
+
+  CGLRendererInfoObj  aRendObj = NULL;
+  CGOpenGLDisplayMask aDispMask = CGDisplayIDToOpenGLDisplayMask (kCGDirectMainDisplay);
+  GLint aRendNb = 0;
+  CGLQueryRendererInfo (aDispMask, &aRendObj, &aRendNb);
+  for (GLint aRendIter = 0; aRendIter < aRendNb; ++aRendIter)
+  {
+    GLint aRendId = 0;
+    if (CGLDescribeRenderer (aRendObj, aRendIter, kCGLRPRendererID, &aRendId) != kCGLNoError
+     || aRendId != aGlRendId)
+    {
+      continue;
+    }
+
+    //kCGLRPVideoMemoryMegabytes   = 131;
+    //kCGLRPTextureMemoryMegabytes = 132;
+    GLint aVMem = 0;
+  #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
+    if (CGLDescribeRenderer(aRendObj, aRendIter, kCGLRPVideoMemoryMegabytes, &aVMem) == kCGLNoError)
+    {
+      addInfo (theDict, "GPU memory",         TCollection_AsciiString() + aVMem + " MiB");
+    }
+    if (CGLDescribeRenderer(aRendObj, aRendIter, kCGLRPTextureMemoryMegabytes, &aVMem) == kCGLNoError)
+    {
+      addInfo (theDict, "GPU Texture memory", TCollection_AsciiString() + aVMem + " MiB");
+    }
+  #else
+    if (CGLDescribeRenderer(aRendObj, aRendIter, kCGLRPVideoMemory, &aVMem) == kCGLNoError)
+    {
+      addInfo (theDict, "GPU memory",         TCollection_AsciiString() + (aVMem / (1024 * 1024)) + " MiB");
+    }
+    if (CGLDescribeRenderer(aRendObj, aRendIter, kCGLRPTextureMemory, &aVMem) == kCGLNoError)
+    {
+      addInfo (theDict, "GPU Texture memory", TCollection_AsciiString() + (aVMem / (1024 * 1024)) + " MiB");
+    }
+  #endif
+  }
+#endif
+
+#if !defined(GL_ES_VERSION_2_0)
+  if (atiMem)
+  {
+    GLint aValues[4];
+    memset (aValues, 0, sizeof(aValues));
+    glGetIntegerv (GL_VBO_FREE_MEMORY_ATI, aValues);
+
+    // total memory free in the pool
+    addInfo (theDict, "GPU free memory",    TCollection_AsciiString() + (aValues[0] / 1024) + " MiB");
+
+    if (aValues[1] != aValues[0])
+    {
+      // largest available free block in the pool
+      addInfo (theDict, "Largest free block", TCollection_AsciiString() + (aValues[1] / 1024) + " MiB");
+    }
     if (aValues[2] != aValues[0])
     {
       // total auxiliary memory free
-      anInfo += TCollection_AsciiString ("  Free memory:        ") + (aValues[2] / 1024) + " MiB\n";
+      addInfo (theDict, "Free auxiliary memory", TCollection_AsciiString() + (aValues[2] / 1024) + " MiB");
     }
   }
   else if (nvxMem)
@@ -2111,25 +2545,140 @@ TCollection_AsciiString OpenGl_Context::MemoryInfo() const
     //current available dedicated video memory (in KiB), currently unused GPU memory
     GLint aValue = 0;
     glGetIntegerv (GL_GPU_MEMORY_INFO_CURRENT_AVAILABLE_VIDMEM_NVX, &aValue);
-    anInfo += TCollection_AsciiString ("  GPU free memory:    ") + (aValue / 1024) + " MiB\n";
+    addInfo (theDict, "GPU free memory", TCollection_AsciiString() + (aValue / 1024) + " MiB");
 
     // dedicated video memory, total size (in KiB) of the GPU memory
     GLint aDedicated = 0;
     glGetIntegerv (GL_GPU_MEMORY_INFO_DEDICATED_VIDMEM_NVX, &aDedicated);
-    anInfo += TCollection_AsciiString ("  GPU memory:         ") + (aDedicated / 1024) + " MiB\n";
+    addInfo (theDict, "GPU memory", TCollection_AsciiString() + (aDedicated / 1024) + " MiB");
 
     // total available memory, total size (in KiB) of the memory available for allocations
     glGetIntegerv (GL_GPU_MEMORY_INFO_TOTAL_AVAILABLE_MEMORY_NVX, &aValue);
     if (aValue != aDedicated)
     {
       // different only for special configurations
-      anInfo += TCollection_AsciiString ("  Total memory:       ") + (aValue / 1024) + " MiB\n";
+      addInfo (theDict, "Total memory", TCollection_AsciiString() + (aValue / 1024) + " MiB");
+    }
+  }
+#endif
+
+#if !defined(GL_ES_VERSION_2_0) && !defined(__APPLE__) && !defined(_WIN32)
+  // GLX_RENDERER_VENDOR_ID_MESA
+  if (myFuncs->glXQueryCurrentRendererIntegerMESA != NULL)
+  {
+    unsigned int aVMemMiB = 0;
+    if (myFuncs->glXQueryCurrentRendererIntegerMESA (GLX_RENDERER_VIDEO_MEMORY_MESA, &aVMemMiB) != False)
+    {
+      addInfo (theDict, "GPU memory", TCollection_AsciiString() + int(aVMemMiB) + " MiB");
     }
   }
 #endif
-  return anInfo;
 }
 
+// =======================================================================
+// function : DiagnosticInfo
+// purpose  :
+// =======================================================================
+void OpenGl_Context::DiagnosticInformation (TColStd_IndexedDataMapOfStringString& theDict,
+                                            Graphic3d_DiagnosticInfo theFlags) const
+{
+  if ((theFlags & Graphic3d_DiagnosticInfo_NativePlatform) != 0)
+  {
+  #if defined(HAVE_EGL)
+    addInfo (theDict, "EGLVersion",    ::eglQueryString ((Aspect_Display)myDisplay, EGL_VERSION));
+    addInfo (theDict, "EGLVendor",     ::eglQueryString ((Aspect_Display)myDisplay, EGL_VENDOR));
+    addInfo (theDict, "EGLClientAPIs", ::eglQueryString ((Aspect_Display)myDisplay, EGL_CLIENT_APIS));
+    if ((theFlags & Graphic3d_DiagnosticInfo_Extensions) != 0)
+    {
+      addInfo (theDict, "EGLExtensions", ::eglQueryString ((Aspect_Display)myDisplay, EGL_EXTENSIONS));
+    }
+  #elif defined(_WIN32)
+    if ((theFlags & Graphic3d_DiagnosticInfo_Extensions) != 0
+     && myFuncs->wglGetExtensionsStringARB != NULL)
+    {
+      const char* aWglExts = myFuncs->wglGetExtensionsStringARB ((HDC )myWindowDC);
+      addInfo (theDict, "WGLExtensions", aWglExts);
+    }
+  #elif defined(__APPLE__)
+    //
+  #else
+    Display* aDisplay = (Display*)myDisplay;
+    const int aScreen = DefaultScreen(aDisplay);
+    addInfo (theDict, "GLXDirectRendering", ::glXIsDirect (aDisplay, (GLXContext )myGContext) ? "Yes" : "No");
+    addInfo (theDict, "GLXVendor",  ::glXQueryServerString (aDisplay, aScreen, GLX_VENDOR));
+    addInfo (theDict, "GLXVersion", ::glXQueryServerString (aDisplay, aScreen, GLX_VERSION));
+    if ((theFlags & Graphic3d_DiagnosticInfo_Extensions) != 0)
+    {
+      const char* aGlxExts = ::glXQueryExtensionsString (aDisplay, aScreen);
+      addInfo(theDict, "GLXExtensions", aGlxExts);
+    }
+
+    addInfo (theDict, "GLXClientVendor",  ::glXGetClientString (aDisplay, GLX_VENDOR));
+    addInfo (theDict, "GLXClientVersion", ::glXGetClientString (aDisplay, GLX_VERSION));
+    if ((theFlags & Graphic3d_DiagnosticInfo_Extensions) != 0)
+    {
+      addInfo (theDict, "GLXClientExtensions", ::glXGetClientString (aDisplay, GLX_EXTENSIONS));
+    }
+  #endif
+  }
+
+  if ((theFlags & Graphic3d_DiagnosticInfo_Device) != 0)
+  {
+    addInfo (theDict, "GLvendor",    (const char*)::glGetString (GL_VENDOR));
+    addInfo (theDict, "GLdevice",    (const char*)::glGetString (GL_RENDERER));
+    addInfo (theDict, "GLversion",   (const char*)::glGetString (GL_VERSION));
+    addInfo (theDict, "GLSLversion", (const char*)::glGetString (GL_SHADING_LANGUAGE_VERSION));
+    if (myIsGlDebugCtx)
+    {
+      addInfo (theDict, "GLdebug", "ON");
+    }
+  }
+
+  if ((theFlags & Graphic3d_DiagnosticInfo_Limits) != 0)
+  {
+    addInfo (theDict, "Max texture size", TCollection_AsciiString(myMaxTexDim));
+    addInfo (theDict, "Max MSAA samples", TCollection_AsciiString(myMaxMsaaSamples));
+  }
+
+  if ((theFlags & Graphic3d_DiagnosticInfo_FrameBuffer) != 0)
+  {
+    GLint aViewport[4] = {};
+    ::glGetIntegerv (GL_VIEWPORT, aViewport);
+    addInfo (theDict, "Viewport", TCollection_AsciiString() + aViewport[2] + "x" + aViewport[3]);
+  }
+
+  if ((theFlags & Graphic3d_DiagnosticInfo_Memory) != 0)
+  {
+    MemoryInfo (theDict);
+  }
+
+  if ((theFlags & Graphic3d_DiagnosticInfo_Extensions) != 0)
+  {
+  #if !defined(GL_ES_VERSION_2_0)
+    if (IsGlGreaterEqual (3, 0)
+     && myFuncs->glGetStringi != NULL)
+    {
+      TCollection_AsciiString anExtList;
+      GLint anExtNb = 0;
+      ::glGetIntegerv (GL_NUM_EXTENSIONS, &anExtNb);
+      for (GLint anIter = 0; anIter < anExtNb; ++anIter)
+      {
+        const char* anExtension = (const char*)myFuncs->glGetStringi (GL_EXTENSIONS, (GLuint)anIter);
+        if (!anExtList.IsEmpty())
+        {
+          anExtList += " ";
+        }
+        anExtList += anExtension;
+      }
+      addInfo(theDict, "GLextensions", anExtList);
+    }
+    else
+  #endif
+    {
+      addInfo (theDict, "GLextensions", (const char*)::glGetString (GL_EXTENSIONS));
+    }
+  }
+}
 
 // =======================================================================
 // function : GetResource
@@ -2165,7 +2714,7 @@ void OpenGl_Context::ReleaseResource (const TCollection_AsciiString& theKey,
   {
     return;
   }
-  const Handle(OpenGl_Resource)& aRes = mySharedResources->Find (theKey);
+  auto& aRes = mySharedResources->Find (theKey);
   if (aRes->GetRefCount() > 1)
   {
     return;
@@ -2182,16 +2731,6 @@ void OpenGl_Context::ReleaseResource (const TCollection_AsciiString& theKey,
   }
 }
 
-// =======================================================================
-// function : DelayedRelease
-// purpose  :
-// =======================================================================
-void OpenGl_Context::DelayedRelease (Handle(OpenGl_Resource)& theResource)
-{
-  myUnusedResources->Prepend (theResource);
-  theResource.Nullify();
-}
-
 // =======================================================================
 // function : ReleaseDelayed
 // purpose  :
@@ -2223,7 +2762,7 @@ void OpenGl_Context::ReleaseDelayed()
       continue;
     }
 
-    Handle(OpenGl_Resource)& aRes = mySharedResources->ChangeFind (aKey);
+    auto& aRes = mySharedResources->ChangeFind (aKey);
     if (aRes->GetRefCount() > 1)
     {
       // should be only 1 instance in mySharedResources
@@ -2254,6 +2793,10 @@ Standard_Boolean OpenGl_Context::BindProgram (const Handle(OpenGl_ShaderProgram)
   {
     return Standard_False;
   }
+  else if (myActiveProgram == theProgram)
+  {
+    return Standard_True;
+  }
 
   if (theProgram.IsNull()
   || !theProgram->IsValid())
@@ -2288,6 +2831,118 @@ void OpenGl_Context::BindDefaultVao()
 #endif
 }
 
+// =======================================================================
+// function : SetDefaultFrameBuffer
+// purpose  :
+// =======================================================================
+Handle(OpenGl_FrameBuffer) OpenGl_Context::SetDefaultFrameBuffer (const Handle(OpenGl_FrameBuffer)& theFbo)
+{
+  Handle(OpenGl_FrameBuffer) aFbo = myDefaultFbo;
+  myDefaultFbo = theFbo;
+  return aFbo;
+}
+
+// =======================================================================
+// function : SetShadingMaterial
+// purpose  :
+// =======================================================================
+void OpenGl_Context::SetShadingMaterial (const OpenGl_AspectFace* theAspect,
+                                         const Handle(Graphic3d_PresentationAttributes)& theHighlight,
+                                         const Standard_Boolean theUseDepthWrite,
+                                         Standard_Integer& theRenderingPassFlags)
+{
+  const Handle(Graphic3d_AspectFillArea3d)& anAspect = (!theHighlight.IsNull() && !theHighlight->BasicFillAreaAspect().IsNull())
+                                                      ?  theHighlight->BasicFillAreaAspect()
+                                                      :  theAspect->Aspect();
+
+  const bool toDistinguish = anAspect->Distinguish();
+  const bool toMapTexture  = anAspect->ToMapTexture();
+  const Graphic3d_MaterialAspect& aMatFrontSrc = anAspect->FrontMaterial();
+  const Graphic3d_MaterialAspect& aMatBackSrc  = toDistinguish
+                                               ? anAspect->BackMaterial()
+                                               : aMatFrontSrc;
+  const Quantity_Color& aFrontIntColor = anAspect->InteriorColor();
+  const Quantity_Color& aBackIntColor  = toDistinguish
+                                       ? anAspect->BackInteriorColor()
+                                       : aFrontIntColor;
+
+  myMatFront.Init (aMatFrontSrc, aFrontIntColor);
+  if (toDistinguish)
+  {
+    myMatBack.Init (aMatBackSrc, aBackIntColor);
+  }
+  else
+  {
+    myMatBack = myMatFront;
+  }
+
+  // handling transparency
+  float aTranspFront = (float )aMatFrontSrc.Transparency();
+  float aTranspBack  = (float )aMatBackSrc .Transparency();
+  if (!theHighlight.IsNull()
+    && theHighlight->BasicFillAreaAspect().IsNull())
+  {
+    myMatFront.SetColor (theHighlight->ColorRGBA());
+    myMatBack .SetColor (theHighlight->ColorRGBA());
+    aTranspFront = theHighlight->Transparency();
+    aTranspBack  = theHighlight->Transparency();
+  }
+  if ((theRenderingPassFlags & OPENGL_NS_2NDPASSDO) != 0)
+  {
+    // second pass
+    myMatFront.Diffuse.a() = aMatFrontSrc.EnvReflexion();
+    myMatBack .Diffuse.a() = aMatBackSrc .EnvReflexion();
+  }
+  else
+  {
+    if (aMatFrontSrc.EnvReflexion() != 0.0f
+     || aMatBackSrc .EnvReflexion() != 0.0f)
+    {
+      // if the material reflects the environment scene, the second pass is needed
+      theRenderingPassFlags |= OPENGL_NS_2NDPASSNEED;
+    }
+
+    GLboolean aDepthMask = GL_TRUE;
+    if (aTranspFront != 0.0f
+     || aTranspBack  != 0.0f)
+    {
+      // render transparent
+      myMatFront.Diffuse.a() = 1.0f - aTranspFront;
+      myMatBack .Diffuse.a() = 1.0f - aTranspBack;
+      glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
+      glEnable (GL_BLEND);
+      aDepthMask = GL_FALSE;
+    }
+    else
+    {
+      // render opaque
+      glBlendFunc (GL_ONE, GL_ZERO);
+      glDisable (GL_BLEND);
+    }
+    if (theUseDepthWrite)
+    {
+      glDepthMask (aDepthMask);
+    }
+  }
+
+  // do not update material properties in case of zero reflection mode,
+  // because GL lighting will be disabled by OpenGl_PrimitiveArray::DrawArray() anyway.
+  if (theAspect->IsNoLighting())
+  {
+    return;
+  }
+
+  if (myMatFront    == myShaderManager->MaterialState().FrontMaterial()
+   && myMatBack     == myShaderManager->MaterialState().BackMaterial()
+   && toDistinguish == myShaderManager->MaterialState().ToDistinguish()
+   && toMapTexture  == myShaderManager->MaterialState().ToMapTexture())
+  {
+    return;
+  }
+
+  myShaderManager->UpdateMaterialStateTo (myMatFront, myMatBack, toDistinguish, toMapTexture);
+}
+
 // =======================================================================
 // function : SetColor4fv
 // purpose  :
@@ -2306,6 +2961,152 @@ void OpenGl_Context::SetColor4fv (const OpenGl_Vec4& theColor)
 #endif
 }
 
+// =======================================================================
+// function : SetTypeOfLine
+// purpose  :
+// =======================================================================
+void OpenGl_Context::SetTypeOfLine (const Aspect_TypeOfLine  theType,
+                                    const Standard_ShortReal theFactor)
+{
+  Standard_Integer aPattern = 0xFFFF;
+  switch (theType)
+  {
+    case Aspect_TOL_DASH:
+    {
+      aPattern = 0xFFC0;
+      break;
+    }
+    case Aspect_TOL_DOT:
+    {
+      aPattern = 0xCCCC;
+      break;
+    }
+    case Aspect_TOL_DOTDASH:
+    {
+      aPattern = 0xFF18;
+      break;
+    }
+    case Aspect_TOL_EMPTY:
+    case Aspect_TOL_SOLID:
+    {
+      aPattern = 0xFFFF;
+      break;
+    }
+    case Aspect_TOL_USERDEFINED:
+    {
+      aPattern = 0xFF24;
+      break;
+    }
+  }
+
+  if (!myActiveProgram.IsNull())
+  {
+    myActiveProgram->SetUniform (this, "uPattern", aPattern);
+    myActiveProgram->SetUniform (this, "uFactor",  theFactor);
+    return;
+  }
+
+#if !defined(GL_ES_VERSION_2_0)
+  if (aPattern != 0xFFFF)
+  {
+  #ifdef HAVE_GL2PS
+    if (IsFeedback())
+    {
+      gl2psEnable (GL2PS_LINE_STIPPLE);
+    }
+  #endif
+
+    if (core11 != NULL)
+    {
+      core11fwd->glEnable (GL_LINE_STIPPLE);
+
+      core11->glLineStipple (static_cast<GLint>    (theFactor),
+                             static_cast<GLushort> (aPattern));
+    }
+  }
+  else
+  {
+    if (core11 != NULL)
+    {
+      core11fwd->glDisable (GL_LINE_STIPPLE);
+    }
+
+  #ifdef HAVE_GL2PS
+    if (IsFeedback())
+    {
+      gl2psDisable (GL2PS_LINE_STIPPLE);
+    }
+  #endif
+  }
+#endif
+}
+
+// =======================================================================
+// function : SetLineWidth
+// purpose  :
+// =======================================================================
+void OpenGl_Context::SetLineWidth (const Standard_ShortReal theWidth)
+{
+  if (core11 != NULL)
+  {
+    // glLineWidth() is still defined within Core Profile, but has no effect with values != 1.0f
+    core11fwd->glLineWidth (theWidth * myResolutionRatio);
+  }
+#ifdef HAVE_GL2PS
+  if (IsFeedback())
+  {
+    gl2psLineWidth (theWidth);
+  }
+#endif
+}
+
+// =======================================================================
+// function : SetTextureMatrix
+// purpose  :
+// =======================================================================
+void OpenGl_Context::SetTextureMatrix (const Handle(Graphic3d_TextureParams)& theParams)
+{
+  if (theParams.IsNull())
+  {
+    return;
+  }
+  else if (!myActiveProgram.IsNull())
+  {
+    const GLint aUniLoc = myActiveProgram->GetStateLocation (OpenGl_OCCT_TEXTURE_TRSF2D);
+    if (aUniLoc == OpenGl_ShaderProgram::INVALID_LOCATION)
+    {
+      return;
+    }
+
+    // pack transformation parameters
+    OpenGl_Vec4 aTrsf[2];
+    aTrsf[0].xy() = theParams->Translation();
+    aTrsf[0].zw() = theParams->Scale();
+    aTrsf[1].x()  = std::sin (-theParams->Rotation() * static_cast<float> (M_PI / 180.0));
+    aTrsf[1].y()  = std::cos (-theParams->Rotation() * static_cast<float> (M_PI / 180.0));
+    myActiveProgram->SetUniform (this, aUniLoc, 2, aTrsf);
+    return;
+  }
+
+#if !defined(GL_ES_VERSION_2_0)
+  if (core11 != NULL)
+  {
+    GLint aMatrixMode = GL_TEXTURE;
+    ::glGetIntegerv (GL_MATRIX_MODE, &aMatrixMode);
+
+    core11->glMatrixMode (GL_TEXTURE);
+    OpenGl_Mat4 aTextureMat;
+    const Graphic3d_Vec2& aScale = theParams->Scale();
+    const Graphic3d_Vec2& aTrans = theParams->Translation();
+    Graphic3d_TransformUtils::Scale     (aTextureMat,  aScale.x(),  aScale.y(), 1.0f);
+    Graphic3d_TransformUtils::Translate (aTextureMat, -aTrans.x(), -aTrans.y(), 0.0f);
+    Graphic3d_TransformUtils::Rotate    (aTextureMat, -theParams->Rotation(), 0.0f, 0.0f, 1.0f);
+    core11->glLoadMatrixf (aTextureMat);
+    core11->glMatrixMode (aMatrixMode);
+  }
+#endif
+}
+
 // =======================================================================
 // function : SetPointSize
 // purpose  :
@@ -2331,6 +3132,27 @@ void OpenGl_Context::SetPointSize (const Standard_ShortReal theSize)
 #endif
 }
 
+// =======================================================================
+// function : SetPointSpriteOrigin
+// purpose  :
+// =======================================================================
+void OpenGl_Context::SetPointSpriteOrigin()
+{
+#if !defined(GL_ES_VERSION_2_0)
+  if (core15fwd == NULL)
+  {
+    return;
+  }
+
+  const int aNewState = !myActiveProgram.IsNull() ? GL_UPPER_LEFT : GL_LOWER_LEFT;
+  if (myPointSpriteOrig != aNewState)
+  {
+    myPointSpriteOrig = aNewState;
+    core15fwd->glPointParameteri (GL_POINT_SPRITE_COORD_ORIGIN, aNewState);
+  }
+#endif
+}
+
 // =======================================================================
 // function : SetGlNormalizeEnabled
 // purpose  :
@@ -2347,13 +3169,16 @@ Standard_Boolean OpenGl_Context::SetGlNormalizeEnabled (Standard_Boolean isEnabl
   myIsGlNormalizeEnabled = isEnabled;
 
 #if !defined(GL_ES_VERSION_2_0)
-  if (isEnabled)
-  {
-    glEnable (GL_NORMALIZE);
-  }
-  else
+  if (core11 != NULL)
   {
-    glDisable (GL_NORMALIZE);
+    if (isEnabled)
+    {
+      ::glEnable  (GL_NORMALIZE);
+    }
+    else
+    {
+      ::glDisable (GL_NORMALIZE);
+    }
   }
 #endif
 
@@ -2361,20 +3186,80 @@ Standard_Boolean OpenGl_Context::SetGlNormalizeEnabled (Standard_Boolean isEnabl
 }
 
 // =======================================================================
-// function : ApplyModelWorldMatrix
+// function : SetPolygonMode
 // purpose  :
 // =======================================================================
-void OpenGl_Context::ApplyModelWorldMatrix()
+Standard_Integer OpenGl_Context::SetPolygonMode (const Standard_Integer theMode)
 {
-#if !defined(GL_ES_VERSION_2_0)
-  if (core11 != NULL)
+  if (myPolygonMode == theMode)
   {
-    core11->glMatrixMode (GL_MODELVIEW);
-    core11->glLoadMatrixf (ModelWorldState.Current());
+    return myPolygonMode;
   }
+
+  const Standard_Integer anOldPolygonMode = myPolygonMode;
+
+  myPolygonMode = theMode;
+
+#if !defined(GL_ES_VERSION_2_0)
+  ::glPolygonMode (GL_FRONT_AND_BACK, (GLenum)theMode);
 #endif
 
-  if (!myShaderManager->IsEmpty())
+  return anOldPolygonMode;
+}
+
+// =======================================================================
+// function : SetPolygonHatchEnabled
+// purpose  :
+// =======================================================================
+bool OpenGl_Context::SetPolygonHatchEnabled (const bool theIsEnabled)
+{
+  if (myHatchStyles.IsNull())
+  {
+    return false;
+  }
+  else if (myHatchStyles->IsEnabled() == theIsEnabled)
+  {
+    return theIsEnabled;
+  }
+
+  return myHatchStyles->SetEnabled (this, theIsEnabled);
+}
+
+// =======================================================================
+// function : SetPolygonHatchStyle
+// purpose  :
+// =======================================================================
+Standard_Integer OpenGl_Context::SetPolygonHatchStyle (const Handle(Graphic3d_HatchStyle)& theStyle)
+{
+  if (theStyle.IsNull())
+  {
+    return 0;
+  }
+
+  if (myHatchStyles.IsNull())
+  {
+    if (!GetResource ("OpenGl_LineAttributes", myHatchStyles))
+    {
+      // share and register for release once the resource is no longer used
+      myHatchStyles = new OpenGl_LineAttributes();
+      ShareResource ("OpenGl_LineAttributes", myHatchStyles);
+    }
+  }
+  if (myHatchStyles->TypeOfHatch() == theStyle->HatchType())
+  {
+    return theStyle->HatchType();
+  }
+
+  return myHatchStyles->SetTypeOfHatch (this, theStyle);
+}
+
+// =======================================================================
+// function : ApplyModelWorldMatrix
+// purpose  :
+// =======================================================================
+void OpenGl_Context::ApplyModelWorldMatrix()
+{
+  if (myShaderManager->ModelWorldState().ModelWorldMatrix() != ModelWorldState.Current())
   {
     myShaderManager->UpdateModelWorldStateTo (ModelWorldState.Current());
   }
@@ -2386,15 +3271,11 @@ void OpenGl_Context::ApplyModelWorldMatrix()
 // =======================================================================
 void OpenGl_Context::ApplyWorldViewMatrix()
 {
-#if !defined(GL_ES_VERSION_2_0)
-  if (core11 != NULL)
+  if (myShaderManager->ModelWorldState().ModelWorldMatrix() != THE_IDENTITY_MATRIX)
   {
-    core11->glMatrixMode (GL_MODELVIEW);
-    core11->glLoadMatrixf (WorldViewState.Current());
+    myShaderManager->UpdateModelWorldStateTo (THE_IDENTITY_MATRIX);
   }
-#endif
-
-  if (!myShaderManager->IsEmpty())
+  if (myShaderManager->WorldViewState().WorldViewMatrix() != WorldViewState.Current())
   {
     myShaderManager->UpdateWorldViewStateTo (WorldViewState.Current());
   }
@@ -2406,19 +3287,13 @@ void OpenGl_Context::ApplyWorldViewMatrix()
 // =======================================================================
 void OpenGl_Context::ApplyModelViewMatrix()
 {
-#if !defined(GL_ES_VERSION_2_0)
-  if (core11 != NULL)
+  if (myShaderManager->ModelWorldState().ModelWorldMatrix() != ModelWorldState.Current())
   {
-    OpenGl_Mat4 aModelView = WorldViewState.Current() * ModelWorldState.Current();
-    core11->glMatrixMode (GL_MODELVIEW);
-    core11->glLoadMatrixf (aModelView.GetData());
+    myShaderManager->UpdateModelWorldStateTo (ModelWorldState.Current());
   }
-#endif
-
-  if (!myShaderManager->IsEmpty())
+  if (myShaderManager->WorldViewState().WorldViewMatrix() != WorldViewState.Current())
   {
-    myShaderManager->UpdateModelWorldStateTo (ModelWorldState.Current());
-    myShaderManager->UpdateWorldViewStateTo (WorldViewState.Current());
+    myShaderManager->UpdateWorldViewStateTo  (WorldViewState.Current());
   }
 }
 
@@ -2428,16 +3303,91 @@ void OpenGl_Context::ApplyModelViewMatrix()
 // =======================================================================
 void OpenGl_Context::ApplyProjectionMatrix()
 {
-#if !defined(GL_ES_VERSION_2_0)
-  if (core11 != NULL)
+  if (myShaderManager->ProjectionState().ProjectionMatrix() != ProjectionState.Current())
   {
-    core11->glMatrixMode (GL_PROJECTION);
-    core11->glLoadMatrixf (ProjectionState.Current().GetData());
+    myShaderManager->UpdateProjectionStateTo (ProjectionState.Current());
   }
+}
+
+// =======================================================================
+// function : EnableFeatures
+// purpose  :
+// =======================================================================
+void OpenGl_Context::EnableFeatures() const
+{
+  //
+}
+
+// =======================================================================
+// function : DisableFeatures
+// purpose  :
+// =======================================================================
+void OpenGl_Context::DisableFeatures() const
+{
+#if !defined(GL_ES_VERSION_2_0)
+  glPixelTransferi (GL_MAP_COLOR, GL_FALSE);
 #endif
 
-  if (!myShaderManager->IsEmpty())
-  {
-    myShaderManager->UpdateProjectionStateTo (ProjectionState.Current());
+  /*
+  * 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_DITHER);
+  glDisable(GL_BLEND);
+  glDisable(GL_DEPTH_TEST);
+  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_TEXTURE_1D);
+
+  glPixelTransferi(GL_MAP_COLOR, GL_FALSE);
+  glPixelTransferi(GL_RED_SCALE, 1);
+  glPixelTransferi(GL_RED_BIAS, 0);
+  glPixelTransferi(GL_GREEN_SCALE, 1);
+  glPixelTransferi(GL_GREEN_BIAS, 0);
+  glPixelTransferi(GL_BLUE_SCALE, 1);
+  glPixelTransferi(GL_BLUE_BIAS, 0);
+  glPixelTransferi(GL_ALPHA_SCALE, 1);
+  glPixelTransferi(GL_ALPHA_BIAS, 0);
+
+  /*
+  * Disable extensions that could slow down glDrawPixels.
+  * (Actually, you should check for the presence of the proper
+  * extension before making these calls.  I've omitted that
+  * code for simplicity.)
+  */
+
+  if ((myGlVerMajor >= 1) && (myGlVerMinor >= 2))
+  {
+#ifdef GL_EXT_convolution
+    if (CheckExtension ("GL_CONVOLUTION_1D_EXT"))
+      glDisable(GL_CONVOLUTION_1D_EXT);
+
+    if (CheckExtension ("GL_CONVOLUTION_2D_EXT"))
+      glDisable(GL_CONVOLUTION_2D_EXT);
+
+    if (CheckExtension ("GL_SEPARABLE_2D_EXT"))
+      glDisable(GL_SEPARABLE_2D_EXT);
+#endif
+
+#ifdef GL_EXT_histogram
+    if (CheckExtension ("GL_SEPARABLE_2D_EXT"))
+      glDisable(GL_HISTOGRAM_EXT);
+
+    if (CheckExtension ("GL_MINMAX_EXT"))
+      glDisable(GL_MINMAX_EXT);
+#endif
+
+#ifdef GL_EXT_texture3D
+    if (CheckExtension ("GL_TEXTURE_3D_EXT"))
+      glDisable(GL_TEXTURE_3D_EXT);
+#endif
   }
+#endif
 }