0026122: Visualization, TKOpenGl - clipping and capping is broken when ffp is disable...
[occt.git] / src / OpenGl / OpenGl_Workspace.cxx
index ad95d7d..ede088c 100644 (file)
 // Alternatively, this file may be used under the terms of Open CASCADE
 // commercial license or contractual agreement.
 
-#include <OpenGl_GlCore15.hxx>
+#include <OpenGl_Workspace.hxx>
 
 #include <InterfaceGraphic.hxx>
 
+#include <OpenGl_ArbFBO.hxx>
 #include <OpenGl_AspectLine.hxx>
 #include <OpenGl_AspectFace.hxx>
 #include <OpenGl_AspectMarker.hxx>
 #include <OpenGl_Context.hxx>
 #include <OpenGl_Element.hxx>
 #include <OpenGl_FrameBuffer.hxx>
+#include <OpenGl_GlCore15.hxx>
+#include <OpenGl_SceneGeometry.hxx>
 #include <OpenGl_Structure.hxx>
 #include <OpenGl_Sampler.hxx>
 #include <OpenGl_Texture.hxx>
-#include <OpenGl_Utils.hxx>
 #include <OpenGl_View.hxx>
-#include <OpenGl_Workspace.hxx>
+#include <OpenGl_Window.hxx>
 
 #include <Graphic3d_TextureParams.hxx>
-
-#if defined(_WIN32) && defined(HAVE_VIDEOCAPTURE)
-  #include <OpenGl_AVIWriter.hxx>
+#include <Graphic3d_TransformUtils.hxx>
+
+#ifdef HAVE_GL2PS
+  #include <gl2ps.h>
+  /* OCC22216 NOTE: linker dependency can be switched off by undefining macro.
+     Pragma comment for gl2ps.lib is defined only here. */
+  #ifdef _MSC_VER
+  #pragma comment( lib, "gl2ps.lib" )
+  #endif
 #endif
 
-IMPLEMENT_STANDARD_HANDLE(OpenGl_Workspace,OpenGl_Window)
-IMPLEMENT_STANDARD_RTTIEXT(OpenGl_Workspace,OpenGl_Window)
-
 namespace
 {
   static const TEL_COLOUR  THE_WHITE_COLOR = { { 1.0f, 1.0f, 1.0f, 1.0f } };
@@ -48,7 +53,6 @@ namespace
   static const OpenGl_AspectLine myDefaultAspectLine;
   static const OpenGl_AspectFace myDefaultAspectFace;
   static const OpenGl_AspectMarker myDefaultAspectMarker;
-  static const OpenGl_AspectText myDefaultAspectText;
 
   static const OpenGl_TextParam myDefaultTextParam =
   {
@@ -135,32 +139,15 @@ void OpenGl_Material::Init (const OPENGL_SURF_PROP& theProp)
 // function : OpenGl_Workspace
 // purpose  :
 // =======================================================================
-OpenGl_Workspace::OpenGl_Workspace (const Handle(OpenGl_GraphicDriver)& theDriver,
-                                    const CALL_DEF_WINDOW&        theCWindow,
-                                    Aspect_RenderingContext       theGContext,
-                                    const Handle(OpenGl_Caps)&    theCaps,
-                                    const Handle(OpenGl_Context)& theShareCtx)
-: OpenGl_Window (theDriver, theCWindow, theGContext, theCaps, theShareCtx),
-  NamedStatus (0),
+OpenGl_Workspace::OpenGl_Workspace (OpenGl_View* theView, const Handle(OpenGl_Window)& theWindow)
+: NamedStatus (0),
   HighlightColor (&THE_WHITE_COLOR),
-  //
-  myComputeInitStatus (OpenGl_RT_NONE),
-  myIsRaytraceDataValid (Standard_False),
-  myIsRaytraceWarnTextures (Standard_False),
-  myViewModificationStatus (0),
-  myLayersModificationStatus (0),
-  //
-  myRaytraceFilter       (new OpenGl_RaytraceFilter()),
-  myToRedrawGL           (Standard_True),
-  myAntiAliasingMode     (3),
-  myTransientDrawToFront (Standard_True),
-  myBackBufferRestored   (Standard_False),
-  myIsImmediateDrawn     (Standard_False),
-  myUseZBuffer (Standard_False),
-  myUseDepthTest (Standard_True),
+  myView (theView),
+  myWindow (theWindow),
+  myGlContext (!theWindow.IsNull() ? theWindow->GetGlContext() : NULL),
+  myUseZBuffer    (Standard_True),
+  myUseDepthWrite (Standard_True),
   myUseGLLight (Standard_True),
-  myIsCullingEnabled (Standard_False),
-  myFrameCounter (0),
   //
   AspectLine_set (&myDefaultAspectLine),
   AspectLine_applied (NULL),
@@ -168,58 +155,48 @@ OpenGl_Workspace::OpenGl_Workspace (const Handle(OpenGl_GraphicDriver)& theDrive
   AspectFace_applied (NULL),
   AspectMarker_set (&myDefaultAspectMarker),
   AspectMarker_applied (NULL),
-  AspectText_set (&myDefaultAspectText),
-  AspectText_applied (NULL),
-  TextParam_set (&myDefaultTextParam),
-  TextParam_applied (NULL),
   ViewMatrix_applied (&myDefaultMatrix),
   StructureMatrix_applied (&myDefaultMatrix),
   myCullingMode (TelCullUndefined),
   myModelViewMatrix (myDefaultMatrix),
   PolygonOffset_applied (THE_DEFAULT_POFFSET)
 {
-  myGlContext->core11fwd->glPixelStorei (GL_UNPACK_ALIGNMENT, 1);
-
-  if (!myGlContext->GetResource ("OpenGl_LineAttributes", myLineAttribs))
+  if (!myGlContext.IsNull() && myGlContext->MakeCurrent())
   {
-    // share and register for release once the resource is no longer used
-    myLineAttribs = new OpenGl_LineAttributes();
-    myGlContext->ShareResource ("OpenGl_LineAttributes", myLineAttribs);
-    myLineAttribs->Init (myGlContext);
-  }
+    myGlContext->core11fwd->glPixelStorei (GL_UNPACK_ALIGNMENT, 1);
 
-  // General initialization of the context
+    if (!myGlContext->GetResource ("OpenGl_LineAttributes", myLineAttribs))
+    {
+      // share and register for release once the resource is no longer used
+      myLineAttribs = new OpenGl_LineAttributes();
+      myGlContext->ShareResource ("OpenGl_LineAttributes", myLineAttribs);
+      myLineAttribs->Init (myGlContext);
+    }
 
-#if !defined(GL_ES_VERSION_2_0)
-  // Eviter d'avoir les faces mal orientees en noir.
-  // Pourrait etre utiliser pour detecter les problemes d'orientation
-  glLightModeli ((GLenum )GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE);
-
-  // Optimisation pour le Fog et l'antialiasing
-  glHint (GL_FOG_HINT,            GL_FASTEST);
-  glHint (GL_POINT_SMOOTH_HINT,   GL_FASTEST);
-  glHint (GL_LINE_SMOOTH_HINT,    GL_FASTEST);
-  glHint (GL_POLYGON_SMOOTH_HINT, GL_FASTEST);
-#endif
+    // General initialization of the context
 
-  // AA mode
-  const char* anAaEnv = ::getenv ("CALL_OPENGL_ANTIALIASING_MODE");
-  if (anAaEnv != NULL)
-  {
-    int v;
-    if (sscanf (anAaEnv, "%d", &v) > 0) myAntiAliasingMode = v;
+  #if !defined(GL_ES_VERSION_2_0)
+    if (myGlContext->core11 != NULL)
+    {
+      // Eviter d'avoir les faces mal orientees en noir.
+      // Pourrait etre utiliser pour detecter les problemes d'orientation
+      glLightModeli ((GLenum )GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE);
+
+      // Optimisation pour le Fog et l'antialiasing
+      glHint (GL_FOG_HINT,            GL_FASTEST);
+      glHint (GL_POINT_SMOOTH_HINT,   GL_FASTEST);
+    }
+
+    glHint (GL_LINE_SMOOTH_HINT,    GL_FASTEST);
+    glHint (GL_POLYGON_SMOOTH_HINT, GL_FASTEST);
+  #endif
   }
-}
 
-// =======================================================================
-// function : SetImmediateModeDrawToFront
-// purpose  :
-// =======================================================================
-Standard_Boolean OpenGl_Workspace::SetImmediateModeDrawToFront (const Standard_Boolean theDrawToFrontBuffer)
-{
-  const Standard_Boolean aPrevMode = myTransientDrawToFront;
-  myTransientDrawToFront = theDrawToFrontBuffer;
-  return aPrevMode;
+  myDefaultCappingAlgoFilter         = new OpenGl_CappingAlgoFilter();
+  myNoneCulling.ChangeCullingMode()  = TelCullNone;
+  myNoneCulling.ChangeEdge()         = 0;
+  myFrontCulling.ChangeCullingMode() = TelCullBack;
+  myFrontCulling.ChangeEdge()        = 0;
 }
 
 // =======================================================================
@@ -233,8 +210,6 @@ OpenGl_Workspace::~OpenGl_Workspace()
     myLineAttribs.Nullify();
     myGlContext->ReleaseResource ("OpenGl_LineAttributes", Standard_True);
   }
-
-  ReleaseRaytraceResources();
 }
 
 // =======================================================================
@@ -243,8 +218,10 @@ OpenGl_Workspace::~OpenGl_Workspace()
 // =======================================================================
 Standard_Boolean OpenGl_Workspace::Activate()
 {
-  if (!OpenGl_Window::Activate())
+  if (myWindow.IsNull() || !myWindow->Activate())
+  {
     return Standard_False;
+  }
 
   ViewMatrix_applied      = &myDefaultMatrix;
   StructureMatrix_applied = &myDefaultMatrix;
@@ -260,6 +237,8 @@ Standard_Boolean OpenGl_Workspace::Activate()
 //=======================================================================
 void OpenGl_Workspace::ResetAppliedAspect()
 {
+  myGlContext->BindDefaultVao();
+
   NamedStatus           = !myTextureBound.IsNull() ? OPENGL_NS_TEXTURE : 0;
   HighlightColor        = &THE_WHITE_COLOR;
   AspectLine_set        = &myDefaultAspectLine;
@@ -268,10 +247,6 @@ void OpenGl_Workspace::ResetAppliedAspect()
   AspectFace_applied    = NULL;
   AspectMarker_set      = &myDefaultAspectMarker;
   AspectMarker_applied  = NULL;
-  AspectText_set        = &myDefaultAspectText;
-  AspectText_applied    = NULL;
-  TextParam_set         = &myDefaultTextParam;
-  TextParam_applied     = NULL;
   PolygonOffset_applied = THE_DEFAULT_POFFSET;
   myCullingMode         = TelCullUndefined;
 
@@ -279,6 +254,9 @@ void OpenGl_Workspace::ResetAppliedAspect()
   AspectFace(Standard_True);
   AspectMarker(Standard_True);
   AspectText(Standard_True);
+
+  myGlContext->SetTypeOfLine (myDefaultAspectLine.Type());
+  myGlContext->SetLineWidth  (myDefaultAspectLine.Width());
 }
 
 // =======================================================================
@@ -292,13 +270,22 @@ Handle(OpenGl_Texture) OpenGl_Workspace::DisableTexture()
     return myTextureBound;
   }
 
+  const Handle(OpenGl_Sampler)& aSampler = myGlContext->TextureSampler();
+  if (!aSampler.IsNull())
+  {
+    aSampler->Unbind (*myGlContext);
+  }
+
 #if !defined(GL_ES_VERSION_2_0)
   // reset texture matrix because some code may expect it is identity
-  GLint aMatrixMode = GL_TEXTURE;
-  glGetIntegerv (GL_MATRIX_MODE, &aMatrixMode);
-  glMatrixMode (GL_TEXTURE);
-  glLoadIdentity();
-  glMatrixMode (aMatrixMode);
+  if (myGlContext->core11 != NULL)
+  {
+    GLint aMatrixMode = GL_TEXTURE;
+    glGetIntegerv (GL_MATRIX_MODE, &aMatrixMode);
+    glMatrixMode (GL_TEXTURE);
+    glLoadIdentity();
+    glMatrixMode (aMatrixMode);
+  }
 #endif
 
   myTextureBound->Unbind (myGlContext);
@@ -307,28 +294,33 @@ Handle(OpenGl_Texture) OpenGl_Workspace::DisableTexture()
   #if !defined(GL_ES_VERSION_2_0)
     case GL_TEXTURE_1D:
     {
-
-      if (myTextureBound->GetParams()->GenMode() != GL_NONE)
+      if (myGlContext->core11 != NULL)
       {
-        glDisable (GL_TEXTURE_GEN_S);
+        if (myTextureBound->GetParams()->GenMode() != GL_NONE)
+        {
+          glDisable (GL_TEXTURE_GEN_S);
+        }
+        glDisable (GL_TEXTURE_1D);
       }
-      glDisable (GL_TEXTURE_1D);
       break;
     }
   #endif
     case GL_TEXTURE_2D:
     {
     #if !defined(GL_ES_VERSION_2_0)
-      if (myTextureBound->GetParams()->GenMode() != GL_NONE)
+      if (myGlContext->core11 != NULL)
       {
-        glDisable (GL_TEXTURE_GEN_S);
-        glDisable (GL_TEXTURE_GEN_T);
-        if (myTextureBound->GetParams()->GenMode() == Graphic3d_TOTM_SPRITE)
+        if (myTextureBound->GetParams()->GenMode() != GL_NONE)
         {
-          glDisable (GL_POINT_SPRITE);
+          glDisable (GL_TEXTURE_GEN_S);
+          glDisable (GL_TEXTURE_GEN_T);
+          if (myTextureBound->GetParams()->GenMode() == Graphic3d_TOTM_SPRITE)
+          {
+            glDisable (GL_POINT_SPRITE);
+          }
         }
+        glDisable (GL_TEXTURE_2D);
       }
-      glDisable (GL_TEXTURE_2D);
     #endif
       break;
     }
@@ -354,81 +346,79 @@ void OpenGl_Workspace::setTextureParams (Handle(OpenGl_Texture)&
   }
 
 #if !defined(GL_ES_VERSION_2_0)
-  GLint aMatrixMode = GL_TEXTURE;
-  glGetIntegerv (GL_MATRIX_MODE, &aMatrixMode);
-
-  // setup texture matrix
-  glMatrixMode (GL_TEXTURE);
-  OpenGl_Mat4 aTextureMat;
-  const Graphic3d_Vec2& aScale = aParams->Scale();
-  const Graphic3d_Vec2& aTrans = aParams->Translation();
-  OpenGl_Utils::Scale     (aTextureMat,  aScale.x(),  aScale.y(), 1.0f);
-  OpenGl_Utils::Translate (aTextureMat, -aTrans.x(), -aTrans.y(), 0.0f);
-  OpenGl_Utils::Rotate    (aTextureMat, -aParams->Rotation(), 0.0f, 0.0f, 1.0f);
-  glLoadMatrixf (aTextureMat);
-
-  // setup generation of texture coordinates
-  switch (aParams->GenMode())
-  {
-    case Graphic3d_TOTM_OBJECT:
+  if (myGlContext->core11 != NULL)
+  {
+    GLint anEnvMode = GL_MODULATE; // lighting mode
+    if (!aParams->IsModulate())
     {
-      glTexGeni  (GL_S, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR);
-      glTexGenfv (GL_S, GL_OBJECT_PLANE,     aParams->GenPlaneS().GetData());
-      if (theTexture->GetTarget() != GL_TEXTURE_1D)
+      anEnvMode = GL_DECAL;
+      if (theTexture->GetFormat() == GL_ALPHA
+       || theTexture->GetFormat() == GL_LUMINANCE)
       {
-        glTexGeni  (GL_T, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR);
-        glTexGenfv (GL_T, GL_OBJECT_PLANE,     aParams->GenPlaneT().GetData());
+        anEnvMode = GL_REPLACE;
       }
-      break;
     }
-    case Graphic3d_TOTM_SPHERE:
+
+    // setup generation of texture coordinates
+    switch (aParams->GenMode())
     {
-      glTexGeni (GL_S, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
-      if (theTexture->GetTarget() != GL_TEXTURE_1D)
+      case Graphic3d_TOTM_OBJECT:
       {
-        glTexGeni (GL_T, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
+        glTexGeni  (GL_S, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR);
+        glTexGenfv (GL_S, GL_OBJECT_PLANE,     aParams->GenPlaneS().GetData());
+        if (theTexture->GetTarget() != GL_TEXTURE_1D)
+        {
+          glTexGeni  (GL_T, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR);
+          glTexGenfv (GL_T, GL_OBJECT_PLANE,     aParams->GenPlaneT().GetData());
+        }
+        break;
       }
-      break;
-    }
-    case Graphic3d_TOTM_EYE:
-    {
-      myGlContext->WorldViewState.Push();
+      case Graphic3d_TOTM_SPHERE:
+      {
+        glTexGeni (GL_S, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
+        if (theTexture->GetTarget() != GL_TEXTURE_1D)
+        {
+          glTexGeni (GL_T, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
+        }
+        break;
+      }
+      case Graphic3d_TOTM_EYE:
+      {
+        myGlContext->WorldViewState.Push();
 
-      myGlContext->WorldViewState.SetIdentity();
-      myGlContext->ApplyWorldViewMatrix();
+        myGlContext->WorldViewState.SetIdentity();
+        myGlContext->ApplyWorldViewMatrix();
 
-      glTexGeni  (GL_S, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR);
-      glTexGenfv (GL_S, GL_EYE_PLANE,        aParams->GenPlaneS().GetData());
+        glTexGeni  (GL_S, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR);
+        glTexGenfv (GL_S, GL_EYE_PLANE,        aParams->GenPlaneS().GetData());
 
-      if (theTexture->GetTarget() != GL_TEXTURE_1D)
-      {
-        glTexGeni  (GL_T, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR);
-        glTexGenfv (GL_T, GL_EYE_PLANE,        aParams->GenPlaneT().GetData());
-      }
+        if (theTexture->GetTarget() != GL_TEXTURE_1D)
+        {
+          glTexGeni  (GL_T, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR);
+          glTexGenfv (GL_T, GL_EYE_PLANE,        aParams->GenPlaneT().GetData());
+        }
 
-      myGlContext->WorldViewState.Pop();
+        myGlContext->WorldViewState.Pop();
 
-      break;
-    }
-    case Graphic3d_TOTM_SPRITE:
-    {
-      if (GetGlContext()->core20 != NULL)
+        break;
+      }
+      case Graphic3d_TOTM_SPRITE:
       {
-        glEnable  (GL_POINT_SPRITE);
-        glTexEnvi (GL_POINT_SPRITE, GL_COORD_REPLACE, GL_TRUE);
-        glTexEnvi (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
-        GetGlContext()->core15->glPointParameteri (GL_POINT_SPRITE_COORD_ORIGIN, GL_LOWER_LEFT);
+        if (myGlContext->core20fwd != NULL)
+        {
+          glEnable  (GL_POINT_SPRITE);
+          glTexEnvi (GL_POINT_SPRITE, GL_COORD_REPLACE, GL_TRUE);
+          anEnvMode = GL_REPLACE;
+          myGlContext->core15->glPointParameteri (GL_POINT_SPRITE_COORD_ORIGIN, GL_LOWER_LEFT);
+        }
+        break;
       }
-      break;
+      case Graphic3d_TOTM_MANUAL:
+      default: break;
     }
-    case Graphic3d_TOTM_MANUAL:
-    default: break;
-  }
 
-  // setup lighting
-  if (aParams->GenMode() != Graphic3d_TOTM_SPRITE)
-  {
-    glTexEnvi (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, aParams->IsModulate() ? GL_MODULATE : GL_DECAL);
+    // setup lighting
+    glTexEnvi (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, anEnvMode);
   }
 #endif
 
@@ -541,32 +531,35 @@ void OpenGl_Workspace::setTextureParams (Handle(OpenGl_Texture)&
   #if !defined(GL_ES_VERSION_2_0)
     case GL_TEXTURE_1D:
     {
-      if (aParams->GenMode() != Graphic3d_TOTM_MANUAL)
+      if (myGlContext->core11 != NULL)
       {
-        glEnable (GL_TEXTURE_GEN_S);
+        if (aParams->GenMode() != Graphic3d_TOTM_MANUAL)
+        {
+          glEnable (GL_TEXTURE_GEN_S);
+        }
+        glEnable (GL_TEXTURE_1D);
       }
-      glEnable (GL_TEXTURE_1D);
       break;
     }
   #endif
     case GL_TEXTURE_2D:
     {
     #if !defined(GL_ES_VERSION_2_0)
-      if (aParams->GenMode() != Graphic3d_TOTM_MANUAL)
+      if (myGlContext->core11 != NULL)
       {
-        glEnable (GL_TEXTURE_GEN_S);
-        glEnable (GL_TEXTURE_GEN_T);
+        if (aParams->GenMode() != Graphic3d_TOTM_MANUAL)
+        {
+          glEnable (GL_TEXTURE_GEN_S);
+          glEnable (GL_TEXTURE_GEN_T);
+        }
+        glEnable (GL_TEXTURE_2D);
       }
-      glEnable (GL_TEXTURE_2D);
     #endif
       break;
     }
     default: break;
   }
 
-#if !defined(GL_ES_VERSION_2_0)
-  glMatrixMode (aMatrixMode); // turn back active matrix
-#endif
   theTexture->SetParams (aParams);
 }
 
@@ -607,352 +600,725 @@ Handle(OpenGl_Texture) OpenGl_Workspace::EnableTexture (const Handle(OpenGl_Text
 }
 
 // =======================================================================
-// function : Redraw
+// function : TelUpdatePolygonOffsets
 // purpose  :
 // =======================================================================
-void OpenGl_Workspace::Redraw (const Graphic3d_CView& theCView,
-                               const Aspect_CLayer2d& theCUnderLayer,
-                               const Aspect_CLayer2d& theCOverLayer)
+static void TelUpdatePolygonOffsets (const TEL_POFFSET_PARAM& theOffsetData)
 {
-  if (!Activate())
+  if ((theOffsetData.mode & Aspect_POM_Fill) == Aspect_POM_Fill)
   {
-    return;
+    glEnable (GL_POLYGON_OFFSET_FILL);
+  }
+  else
+  {
+    glDisable (GL_POLYGON_OFFSET_FILL);
   }
 
-  ++myFrameCounter;
-  myIsCullingEnabled = theCView.IsCullingEnabled;
-
-  // release pending GL resources
-  Handle(OpenGl_Context) aGlCtx = GetGlContext();
-  aGlCtx->ReleaseDelayed();
-
-  // fetch OpenGl context state
-  aGlCtx->FetchState();
+#if !defined(GL_ES_VERSION_2_0)
+  if ((theOffsetData.mode & Aspect_POM_Line) == Aspect_POM_Line)
+  {
+    glEnable (GL_POLYGON_OFFSET_LINE);
+  }
+  else
+  {
+    glDisable (GL_POLYGON_OFFSET_LINE);
+  }
 
-  Tint toSwap = (aGlCtx->IsRender() && !aGlCtx->caps->buffersNoSwap) ? 1 : 0; // swap buffers
-  OpenGl_FrameBuffer* aFrameBuffer = (OpenGl_FrameBuffer* )theCView.ptrFBO;
-  if (aFrameBuffer != NULL)
+  if ((theOffsetData.mode & Aspect_POM_Point) == Aspect_POM_Point)
   {
-    aFrameBuffer->SetupViewport (aGlCtx);
-    toSwap = 0; // no need to swap buffers
+    glEnable (GL_POLYGON_OFFSET_POINT);
   }
   else
   {
-    aGlCtx->core11fwd->glViewport (0, 0, myWidth, myHeight);
+    glDisable (GL_POLYGON_OFFSET_POINT);
   }
+#endif
 
-  myToRedrawGL = Standard_True;
-  if (theCView.RenderParams.Method == Graphic3d_RM_RAYTRACING
-   && myComputeInitStatus != OpenGl_RT_FAIL)
+  glPolygonOffset (theOffsetData.factor, theOffsetData.units);
+}
+
+// =======================================================================
+// function : updateMaterial
+// purpose  :
+// =======================================================================
+void OpenGl_Workspace::updateMaterial (const int theFlag)
+{
+  // Case of hidden line
+  if (AspectFace_set->InteriorStyle() == Aspect_IS_HIDDENLINE)
   {
-    if (UpdateRaytraceGeometry (OpenGl_GUM_CHECK) && myIsRaytraceDataValid)
-    {
-      myToRedrawGL = Standard_False;
+    myAspectFaceHl = *AspectFace_set; // copy all values including line edge aspect
+    myAspectFaceHl.ChangeIntFront().matcol     = myView->BackgroundColor();
+    myAspectFaceHl.ChangeIntFront().color_mask = 0;
+    myAspectFaceHl.ChangeIntFront().color_mask = 0;
 
-      // Only non-raytracable structures should be rendered in OpenGL mode.
-      Handle(OpenGl_RenderFilter) aRenderFilter = GetRenderFilter();
-      myRaytraceFilter->SetPrevRenderFilter (aRenderFilter);
-      SetRenderFilter (myRaytraceFilter);
+    AspectFace_set = &myAspectFaceHl;
+    return;
+  }
 
-      Standard_Integer aSizeX = aFrameBuffer != NULL ? aFrameBuffer->GetVPSizeX() : myWidth;
-      Standard_Integer aSizeY = aFrameBuffer != NULL ? aFrameBuffer->GetVPSizeY() : myHeight;
+  const OPENGL_SURF_PROP* aProps = &AspectFace_set->IntFront();
+  GLenum aFace = GL_FRONT_AND_BACK;
+  if (theFlag == TEL_BACK_MATERIAL)
+  {
+    aFace  = GL_BACK;
+    aProps = &AspectFace_set->IntBack();
+  }
+  else if (AspectFace_set->DistinguishingMode() == TOn
+        && !(NamedStatus & OPENGL_NS_RESMAT))
+  {
+    aFace = GL_FRONT;
+  }
+
+  myMatTmp.Init (*aProps);
 
-      if (myOpenGlFBO.IsNull())
+  // handling transparency
+  if (NamedStatus & OPENGL_NS_2NDPASSDO)
+  {
+    // second pass
+    myMatTmp.Diffuse.a() = aProps->env_reflexion;
+  }
+  else
+  {
+    if (aProps->env_reflexion != 0.0f)
+    {
+      // if the material reflects the environment scene, the second pass is needed
+      NamedStatus |= OPENGL_NS_2NDPASSNEED;
+    }
+
+    if (aProps->trans != 1.0f)
+    {
+      // render transparent
+      myMatTmp.Diffuse.a() = aProps->trans;
+      glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
+      glEnable    (GL_BLEND);
+      if (myUseDepthWrite)
       {
-        myOpenGlFBO = new OpenGl_FrameBuffer();
+        glDepthMask (GL_FALSE);
       }
-      if (myOpenGlFBO->GetVPSizeX() != aSizeX
-       || myOpenGlFBO->GetVPSizeY() != aSizeY)
+    }
+    else
+    {
+      // render opaque
+      if ((NamedStatus & OPENGL_NS_ANTIALIASING) == 0)
       {
-        myOpenGlFBO->Init (aGlCtx, aSizeX, aSizeY);
+        glBlendFunc (GL_ONE, GL_ZERO);
+        glDisable   (GL_BLEND);
       }
-
-      // OverLayer and UnderLayer shouldn't be drawn by OpenGL.
-      // They will be drawn during ray-tracing.
-      Aspect_CLayer2d anEmptyCLayer;
-      anEmptyCLayer.ptrLayer = NULL;
-
-      myOpenGlFBO->BindBuffer (aGlCtx);
-      redraw1 (theCView, anEmptyCLayer, anEmptyCLayer, 0);
-      myOpenGlFBO->UnbindBuffer (aGlCtx);
-
-      const Standard_Boolean isImmediate = !myView->ImmediateStructures().IsEmpty();
-      Raytrace (theCView, aSizeX, aSizeY, isImmediate ? 0 : toSwap,
-                theCOverLayer, theCUnderLayer, aFrameBuffer);
-
-      if (isImmediate)
+      if (myUseDepthWrite)
       {
-        RedrawImmediate (theCView, theCUnderLayer, theCOverLayer, Standard_True);
+        glDepthMask (GL_TRUE);
       }
-
-      SetRenderFilter (aRenderFilter);
-
-      theCView.WasRedrawnGL = Standard_False;
     }
   }
 
-  if (myToRedrawGL)
+  // do not update material properties in case of zero reflection mode,
+  // because GL lighting will be disabled by OpenGl_PrimitiveArray::DrawArray() anyway.
+  if (aProps->color_mask == 0)
+  {
+    return;
+  }
+
+  // reset material
+  if (NamedStatus & OPENGL_NS_RESMAT)
   {
-    // draw entire frame using normal OpenGL pipeline
-    if (aFrameBuffer != NULL)
+  #if !defined(GL_ES_VERSION_2_0)
+    if (myGlContext->core11 != NULL)
     {
-      aFrameBuffer->BindBuffer (aGlCtx);
+      myGlContext->core11->glMaterialfv (aFace, GL_AMBIENT,   myMatTmp.Ambient.GetData());
+      myGlContext->core11->glMaterialfv (aFace, GL_DIFFUSE,   myMatTmp.Diffuse.GetData());
+      myGlContext->core11->glMaterialfv (aFace, GL_SPECULAR,  myMatTmp.Specular.GetData());
+      myGlContext->core11->glMaterialfv (aFace, GL_EMISSION,  myMatTmp.Emission.GetData());
+      myGlContext->core11->glMaterialf  (aFace, GL_SHININESS, myMatTmp.Shine());
     }
+  #endif
 
-    const Standard_Boolean isImmediate = !myView->ImmediateStructures().IsEmpty();
-    redraw1 (theCView, theCUnderLayer, theCOverLayer, isImmediate ? 0 : toSwap);
-    if (isImmediate)
+    if (theFlag == TEL_FRONT_MATERIAL)
     {
-      RedrawImmediate (theCView, theCUnderLayer, theCOverLayer, Standard_True);
+      myMatFront = myMatTmp;
+      myMatBack  = myMatTmp;
+    }
+    else
+    {
+      myMatBack = myMatTmp;
     }
 
-    theCView.WasRedrawnGL = Standard_True;
+    NamedStatus &= ~OPENGL_NS_RESMAT;
+    return;
   }
 
-  if (aFrameBuffer != NULL)
+  // reduce updates
+  OpenGl_Material& anOld = (theFlag == TEL_FRONT_MATERIAL)
+                         ? myMatFront
+                         : myMatBack;
+#if !defined(GL_ES_VERSION_2_0)
+  if (myGlContext->core11 != NULL)
   {
-    aFrameBuffer->UnbindBuffer (aGlCtx);
-    // move back original viewport
-    aGlCtx->core11fwd->glViewport (0, 0, myWidth, myHeight);
+    if (myMatTmp.Ambient.r() != anOld.Ambient.r()
+     || myMatTmp.Ambient.g() != anOld.Ambient.g()
+     || myMatTmp.Ambient.b() != anOld.Ambient.b())
+    {
+      myGlContext->core11->glMaterialfv (aFace, GL_AMBIENT, myMatTmp.Ambient.GetData());
+    }
+    if (myMatTmp.Diffuse.r() != anOld.Diffuse.r()
+     || myMatTmp.Diffuse.g() != anOld.Diffuse.g()
+     || myMatTmp.Diffuse.b() != anOld.Diffuse.b()
+     || fabs (myMatTmp.Diffuse.a() - anOld.Diffuse.a()) > 0.01f)
+    {
+      myGlContext->core11->glMaterialfv (aFace, GL_DIFFUSE, myMatTmp.Diffuse.GetData());
+    }
+    if (myMatTmp.Specular.r() != anOld.Specular.r()
+     || myMatTmp.Specular.g() != anOld.Specular.g()
+     || myMatTmp.Specular.b() != anOld.Specular.b())
+    {
+      myGlContext->core11->glMaterialfv (aFace, GL_SPECULAR, myMatTmp.Specular.GetData());
+    }
+    if (myMatTmp.Emission.r() != anOld.Emission.r()
+     || myMatTmp.Emission.g() != anOld.Emission.g()
+     || myMatTmp.Emission.b() != anOld.Emission.b())
+    {
+      myGlContext->core11->glMaterialfv (aFace, GL_EMISSION, myMatTmp.Emission.GetData());
+    }
+    if (myMatTmp.Shine() != anOld.Shine())
+    {
+      myGlContext->core11->glMaterialf (aFace, GL_SHININESS, myMatTmp.Shine());
+    }
   }
-
-#if defined(_WIN32) && defined(HAVE_VIDEOCAPTURE)
-  if (OpenGl_AVIWriter_AllowWriting (theCView.DefWindow.XWindow))
+#endif
+  anOld = myMatTmp;
+  if (aFace == GL_FRONT_AND_BACK)
   {
-    GLint params[4];
-    glGetIntegerv (GL_VIEWPORT, params);
-    int nWidth  = params[2] & ~0x7;
-    int nHeight = params[3] & ~0x7;
+    myMatBack = myMatTmp;
+  }
+}
+
+// =======================================================================
+// function : SetAspectLine
+// purpose  :
+// =======================================================================
+const OpenGl_AspectLine * OpenGl_Workspace::SetAspectLine(const OpenGl_AspectLine *AnAspect)
+{
+  const OpenGl_AspectLine *AspectLine_old = AspectLine_set;
+  AspectLine_set = AnAspect;
+  return AspectLine_old;
+}
 
-    const int nBitsPerPixel = 24;
-    GLubyte* aDumpData = new GLubyte[nWidth * nHeight * nBitsPerPixel / 8];
+// =======================================================================
+// function : SetAspectFace
+// purpose  :
+// =======================================================================
+const OpenGl_AspectFace * OpenGl_Workspace::SetAspectFace(const OpenGl_AspectFace *AnAspect)
+{
+  const OpenGl_AspectFace *AspectFace_old = AspectFace_set;
+  AspectFace_set = AnAspect;
+  return AspectFace_old;
+}
 
-    glPixelStorei (GL_PACK_ALIGNMENT, 1);
-    glReadPixels (0, 0, nWidth, nHeight, GL_BGR_EXT, GL_UNSIGNED_BYTE, aDumpData);
-    OpenGl_AVIWriter_AVIWriter (aDumpData, nWidth, nHeight, nBitsPerPixel);
-    delete[] aDumpData;
-  }
-#endif
+// =======================================================================
+// function : SetAspectMarker
+// purpose  :
+// =======================================================================
+const OpenGl_AspectMarker * OpenGl_Workspace::SetAspectMarker(const OpenGl_AspectMarker *AnAspect)
+{
+  const OpenGl_AspectMarker *AspectMarker_old = AspectMarker_set;
+  AspectMarker_set = AnAspect;
+  return AspectMarker_old;
+}
 
-  // reset render mode state
-  aGlCtx->FetchState();
+// =======================================================================
+// function : SetAspectText
+// purpose  :
+// =======================================================================
+const OpenGl_AspectText * OpenGl_Workspace::SetAspectText(const OpenGl_AspectText *AnAspect)
+{
+  const OpenGl_AspectText *AspectText_old = AspectText_set;
+  AspectText_set = AnAspect;
+  return AspectText_old;
 }
 
 // =======================================================================
-// function : redraw1
+// function : AspectLine
 // purpose  :
 // =======================================================================
-void OpenGl_Workspace::redraw1 (const Graphic3d_CView& theCView,
-                                const Aspect_CLayer2d& theCUnderLayer,
-                                const Aspect_CLayer2d& theCOverLayer,
-                                const int              theToSwap)
+const OpenGl_AspectLine * OpenGl_Workspace::AspectLine(const Standard_Boolean theWithApply)
 {
-  if (myView.IsNull())
+  if (theWithApply)
   {
-    return;
+    AspectLine_applied = AspectLine_set;
   }
 
-  // request reset of material
-  NamedStatus |= OPENGL_NS_RESMAT;
+  return AspectLine_set;
+}
 
-  GLbitfield toClear = GL_COLOR_BUFFER_BIT;
-  if (myUseZBuffer)
+// =======================================================================
+// function : AspectFace
+// purpose  :
+// =======================================================================
+const OpenGl_AspectFace* OpenGl_Workspace::AspectFace (const Standard_Boolean theToApply)
+{
+  if (!theToApply)
   {
-    glDepthFunc (GL_LEQUAL);
-    glDepthMask (GL_TRUE);
-    if (myUseDepthTest)
+    return AspectFace_set;
+  }
+
+  if (myView->BackfacingModel() == Graphic3d_TOBM_AUTOMATIC)
+  {
+    // manage back face culling mode, disable culling when clipping is enabled
+    TelCullMode aCullingMode = (myGlContext->Clipping().IsClippingOrCappingOn()
+                             || AspectFace_set->InteriorStyle() == Aspect_IS_HATCH)
+                             ? TelCullNone
+                             : (TelCullMode )AspectFace_set->CullingMode();
+    if (aCullingMode != TelCullNone
+     && !(NamedStatus & OPENGL_NS_2NDPASSDO))
     {
-      glEnable (GL_DEPTH_TEST);
+      // disable culling in case of translucent shading aspect
+      if (AspectFace_set->IntFront().trans != 1.0f)
+      {
+        aCullingMode = TelCullNone;
+      }
     }
-    else
+    if (myCullingMode != aCullingMode)
     {
-      glDisable (GL_DEPTH_TEST);
+      myCullingMode = aCullingMode;
+      switch (myCullingMode)
+      {
+        case TelCullNone:
+        case TelCullUndefined:
+        {
+          glDisable (GL_CULL_FACE);
+          break;
+        }
+        case TelCullFront:
+        {
+          glCullFace (GL_FRONT);
+          glEnable (GL_CULL_FACE);
+          break;
+        }
+        case TelCullBack:
+        {
+          glCullFace (GL_BACK);
+          glEnable (GL_CULL_FACE);
+          break;
+        }
+      }
     }
-
-  #if !defined(GL_ES_VERSION_2_0)
-    glClearDepth (1.0);
-  #else
-    glClearDepthf (1.0f);
-  #endif
-    toClear |= GL_DEPTH_BUFFER_BIT;
   }
-  else
+
+  if (AspectFace_set == AspectFace_applied)
   {
-    glDisable (GL_DEPTH_TEST);
+    return AspectFace_set;
   }
 
-  if (!ToRedrawGL())
+#if !defined(GL_ES_VERSION_2_0)
+  const Aspect_InteriorStyle anIntstyle = AspectFace_set->InteriorStyle();
+  if (AspectFace_applied == NULL || AspectFace_applied->InteriorStyle() != anIntstyle)
   {
-    // set background to black
-    glClearColor (0.0f, 0.0f, 0.0f, 0.0f);
-    toClear |= GL_DEPTH_BUFFER_BIT; //
+    switch (anIntstyle)
+    {
+      case Aspect_IS_EMPTY:
+      case Aspect_IS_HOLLOW:
+      {
+        glPolygonMode (GL_FRONT_AND_BACK, GL_LINE);
+        break;
+      }
+      case Aspect_IS_HATCH:
+      {
+        glPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
+        myLineAttribs->SetTypeOfHatch (AspectFace_applied != NULL ? AspectFace_applied->Hatch() : TEL_HS_SOLID);
+        break;
+      }
+      case Aspect_IS_SOLID:
+      case Aspect_IS_HIDDENLINE:
+      {
+        glPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
+        if (myGlContext->core11 != NULL)
+        {
+          glDisable (GL_POLYGON_STIPPLE);
+        }
+        break;
+      }
+      case Aspect_IS_POINT:
+      {
+        glPolygonMode (GL_FRONT_AND_BACK, GL_POINT);
+        break;
+      }
+    }
   }
-  else
+
+  if (anIntstyle == Aspect_IS_HATCH)
   {
-    if (NamedStatus & OPENGL_NS_WHITEBACK)
+    const Tint hatchstyle = AspectFace_set->Hatch();
+    if (AspectFace_applied == NULL || AspectFace_applied->Hatch() != hatchstyle)
     {
-        // set background to white
-      glClearColor (1.0f, 1.0f, 1.0f, 1.0f);
-      toClear |= GL_DEPTH_BUFFER_BIT;
+      myLineAttribs->SetTypeOfHatch (hatchstyle);
     }
-    else
+  }
+#endif
+
+  // Aspect_POM_None means: do not change current settings
+  if ((AspectFace_set->PolygonOffset().mode & Aspect_POM_None) != Aspect_POM_None)
+  {
+    if (PolygonOffset_applied.mode   != AspectFace_set->PolygonOffset().mode
+     || PolygonOffset_applied.factor != AspectFace_set->PolygonOffset().factor
+     || PolygonOffset_applied.units  != AspectFace_set->PolygonOffset().units)
     {
-      glClearColor (myBgColor.rgb[0], myBgColor.rgb[1], myBgColor.rgb[2], 0.0f);
+      SetPolygonOffset (AspectFace_set->PolygonOffset().mode,
+                        AspectFace_set->PolygonOffset().factor,
+                        AspectFace_set->PolygonOffset().units);
     }
   }
-  glClear (toClear);
-
-  Handle(OpenGl_Workspace) aWS (this);
-  myView->Render (myPrintContext, aWS, theCView, theCUnderLayer, theCOverLayer);
 
-  // swap the buffers
-  if (theToSwap)
+  updateMaterial (TEL_FRONT_MATERIAL);
+  if (AspectFace_set->DistinguishingMode() == TOn)
   {
-    GetGlContext()->SwapBuffers();
-    myBackBufferRestored = Standard_False;
-    myIsImmediateDrawn   = Standard_False;
+    updateMaterial (TEL_BACK_MATERIAL);
   }
-  else
+
+  if ((NamedStatus & OPENGL_NS_FORBIDSETTEX) == 0)
   {
-    glFlush(); //
-    myBackBufferRestored = Standard_True;//
-    myIsImmediateDrawn   = Standard_False;//
+    if (AspectFace_set->DoTextureMap())
+    {
+      EnableTexture (AspectFace_set->TextureRes (myGlContext),
+                     AspectFace_set->TextureParams());
+    }
+    else
+    {
+      DisableTexture();
+    }
   }
+
+  AspectFace_applied = AspectFace_set;
+  return AspectFace_set;
+}
+
+//=======================================================================
+//function : SetPolygonOffset
+//purpose  :
+//=======================================================================
+void OpenGl_Workspace::SetPolygonOffset (int theMode,
+                                         Standard_ShortReal theFactor,
+                                         Standard_ShortReal theUnits)
+{
+  PolygonOffset_applied.mode   = theMode;
+  PolygonOffset_applied.factor = theFactor;
+  PolygonOffset_applied.units  = theUnits;
+
+  TelUpdatePolygonOffsets (PolygonOffset_applied);
 }
 
 // =======================================================================
-// function : copyBackToFront
+// function : AspectMarker
 // purpose  :
 // =======================================================================
-void OpenGl_Workspace::copyBackToFront()
+const OpenGl_AspectMarker* OpenGl_Workspace::AspectMarker (const Standard_Boolean theToApply)
 {
-#if !defined(GL_ES_VERSION_2_0)
-
-  OpenGl_Mat4 aProjectMat;
-  OpenGl_Utils::Ortho2D<Standard_ShortReal> (aProjectMat,
-    0.f, static_cast<GLfloat> (myWidth), 0.f, static_cast<GLfloat> (myHeight));
+  if (theToApply && (AspectMarker_set != AspectMarker_applied))
+  {
+    if (!AspectMarker_applied || (AspectMarker_set->Scale() != AspectMarker_applied->Scale()))
+    {
+    #if !defined(GL_ES_VERSION_2_0)
+      glPointSize (AspectMarker_set->Scale());
+    #ifdef HAVE_GL2PS
+      gl2psPointSize (AspectMarker_set->Scale());
+    #endif
+    #endif
+    }
+    AspectMarker_applied = AspectMarker_set;
+  }
+  return AspectMarker_set;
+}
 
-  myGlContext->WorldViewState.Push();
-  myGlContext->ProjectionState.Push();
+// =======================================================================
+// function : AspectText
+// purpose  :
+// =======================================================================
+const OpenGl_AspectText* OpenGl_Workspace::AspectText (const Standard_Boolean theWithApply)
+{
+  if (theWithApply)
+  {
+    AspectText_applied = AspectText_set;
+  }
 
-  myGlContext->WorldViewState.SetIdentity();
-  myGlContext->ProjectionState.SetCurrent (aProjectMat);
+  return AspectText_set;
+}
 
-  myGlContext->ApplyProjectionMatrix();
-  myGlContext->ApplyWorldViewMatrix();
+// =======================================================================
+// function : Width
+// purpose  :
+// =======================================================================
+Standard_Integer OpenGl_Workspace::Width()  const
+{
+  return !myView->GlWindow().IsNull() ? myView->GlWindow()->Width() : 0;
+}
 
-  DisableFeatures();
+// =======================================================================
+// function : Height
+// purpose  :
+// =======================================================================
+Standard_Integer OpenGl_Workspace::Height() const
+{
+  return !myView->GlWindow().IsNull() ? myView->GlWindow()->Height() : 0;
+}
 
-  glDrawBuffer (GL_FRONT);
-  glReadBuffer (GL_BACK);
+// =======================================================================
+// function : UseGLLight
+// purpose  :
+// =======================================================================
+Standard_Boolean OpenGl_Workspace::UseGLLight() const
+{
+  return myView->IsGLLightEnabled();
+}
 
-  glRasterPos2i (0, 0);
-  glCopyPixels  (0, 0, myWidth + 1, myHeight + 1, GL_COLOR);
+// =======================================================================
+// function : AntiAliasingMode
+// purpose  :
+// =======================================================================
+Standard_Integer OpenGl_Workspace::AntiAliasingMode() const
+{
+  return myView->IsAntialiasingEnabled();
+}
 
-  EnableFeatures();
+// =======================================================================
+// function : IsCullingEnabled
+// purpose  :
+// =======================================================================
+Standard_Boolean OpenGl_Workspace::IsCullingEnabled() const
+{
+  return myView->IsCullingEnabled();
+}
 
-  myGlContext->WorldViewState.Pop();
-  myGlContext->ProjectionState.Pop();
-  myGlContext->ApplyProjectionMatrix();
-  glDrawBuffer (GL_BACK);
+// =======================================================================
+// function : FBOCreate
+// purpose  :
+// =======================================================================
+Graphic3d_PtrFrameBuffer OpenGl_Workspace::FBOCreate (const Standard_Integer theWidth,
+                                                      const Standard_Integer theHeight)
+{
+  // activate OpenGL context
+  if (!Activate())
+    return NULL;
 
-#endif
-  myIsImmediateDrawn = Standard_False;
+  // create the FBO
+  const Handle(OpenGl_Context)& aCtx = GetGlContext();
+  OpenGl_FrameBuffer* aFrameBuffer = new OpenGl_FrameBuffer();
+  if (!aFrameBuffer->Init (aCtx, theWidth, theHeight))
+  {
+    aFrameBuffer->Release (aCtx.operator->());
+    delete aFrameBuffer;
+    return NULL;
+  }
+  return (Graphic3d_PtrFrameBuffer )aFrameBuffer;
 }
 
 // =======================================================================
-// function : DisplayCallback
+// function : FBORelease
 // purpose  :
 // =======================================================================
-void OpenGl_Workspace::DisplayCallback (const Graphic3d_CView& theCView,
-                                        Standard_Integer       theReason)
+void OpenGl_Workspace::FBORelease (Graphic3d_PtrFrameBuffer theFBOPtr)
 {
-  if (theCView.GDisplayCB == NULL)
+  // activate OpenGL context
+  if (!Activate()
+   || theFBOPtr == NULL)
   {
     return;
   }
 
-  Aspect_GraphicCallbackStruct aCallData;
-  aCallData.reason    = theReason;
-  aCallData.glContext = GetGlContext();
-  aCallData.wsID      = theCView.WsId;
-  aCallData.viewID    = theCView.ViewId;
-  theCView.GDisplayCB (theCView.DefWindow.XWindow, theCView.GClientData, &aCallData);
+  // release the object
+  OpenGl_FrameBuffer* aFrameBuffer = (OpenGl_FrameBuffer*)theFBOPtr;
+  if (aFrameBuffer != NULL)
+  {
+    aFrameBuffer->Release (GetGlContext().operator->());
+  }
+  delete aFrameBuffer;
+}
+
+inline bool getDataFormat (const Image_PixMap& theData,
+                           GLenum&             thePixelFormat,
+                           GLenum&             theDataType)
+{
+  thePixelFormat = GL_RGB;
+  theDataType    = GL_UNSIGNED_BYTE;
+  switch (theData.Format())
+  {
+  #if !defined(GL_ES_VERSION_2_0)
+    case Image_PixMap::ImgGray:
+      thePixelFormat = GL_DEPTH_COMPONENT;
+      theDataType    = GL_UNSIGNED_BYTE;
+      return true;
+    case Image_PixMap::ImgGrayF:
+      thePixelFormat = GL_DEPTH_COMPONENT;
+      theDataType    = GL_FLOAT;
+      return true;
+    case Image_PixMap::ImgBGR:
+      thePixelFormat = GL_BGR;
+      theDataType    = GL_UNSIGNED_BYTE;
+      return true;
+    case Image_PixMap::ImgBGRA:
+    case Image_PixMap::ImgBGR32:
+      thePixelFormat = GL_BGRA;
+      theDataType    = GL_UNSIGNED_BYTE;
+      return true;
+    case Image_PixMap::ImgBGRF:
+      thePixelFormat = GL_BGR;
+      theDataType    = GL_FLOAT;
+      return true;
+    case Image_PixMap::ImgBGRAF:
+      thePixelFormat = GL_BGRA;
+      theDataType    = GL_FLOAT;
+      return true;
+  #else
+    case Image_PixMap::ImgGray:
+    case Image_PixMap::ImgGrayF:
+    case Image_PixMap::ImgBGR:
+    case Image_PixMap::ImgBGRA:
+    case Image_PixMap::ImgBGR32:
+    case Image_PixMap::ImgBGRF:
+    case Image_PixMap::ImgBGRAF:
+      return false;
+  #endif
+    case Image_PixMap::ImgRGB:
+      thePixelFormat = GL_RGB;
+      theDataType    = GL_UNSIGNED_BYTE;
+      return true;
+    case Image_PixMap::ImgRGBA:
+    case Image_PixMap::ImgRGB32:
+      thePixelFormat = GL_RGBA;
+      theDataType    = GL_UNSIGNED_BYTE;
+      return true;
+    case Image_PixMap::ImgRGBF:
+      thePixelFormat = GL_RGB;
+      theDataType    = GL_FLOAT;
+      return true;
+    case Image_PixMap::ImgRGBAF:
+      thePixelFormat = GL_RGBA;
+      theDataType    = GL_FLOAT;
+      return true;
+    case Image_PixMap::ImgAlpha:
+    case Image_PixMap::ImgAlphaF:
+      return false; // GL_ALPHA is no more supported in core context
+    case Image_PixMap::ImgUNKNOWN:
+      return false;
+  }
+  return false;
 }
 
 // =======================================================================
-// function : RedrawImmediate
+// function : getAligned
 // purpose  :
 // =======================================================================
-void OpenGl_Workspace::RedrawImmediate (const Graphic3d_CView& theCView,
-                                        const Aspect_CLayer2d& theCUnderLayer,
-                                        const Aspect_CLayer2d& theCOverLayer,
-                                        const Standard_Boolean theToForce)
+inline Standard_Size getAligned (const Standard_Size theNumber,
+                                 const Standard_Size theAlignment)
 {
-  if (!Activate())
+  return theNumber + theAlignment - 1 - (theNumber - 1) % theAlignment;
+}
+
+// =======================================================================
+// function : BufferDump
+// purpose  :
+// =======================================================================
+Standard_Boolean OpenGl_Workspace::BufferDump (OpenGl_FrameBuffer*         theFBOPtr,
+                                               Image_PixMap&               theImage,
+                                               const Graphic3d_BufferType& theBufferType)
+{
+  GLenum aFormat, aType;
+  if (theImage.IsEmpty()
+   || !getDataFormat (theImage, aFormat, aType)
+   || !Activate())
   {
-    return;
+    return Standard_False;
   }
-
-  GLboolean isDoubleBuffer = GL_FALSE;
 #if !defined(GL_ES_VERSION_2_0)
-  glGetBooleanv (GL_DOUBLEBUFFER, &isDoubleBuffer);
+  GLint aReadBufferPrev = GL_BACK;
+  if (theBufferType == Graphic3d_BT_Depth
+   && aFormat != GL_DEPTH_COMPONENT)
+  {
+    return Standard_False;
+  }
 #endif
-  if (myView->ImmediateStructures().IsEmpty())
+
+  // bind FBO if used
+  if (theFBOPtr != NULL && theFBOPtr->IsValid())
   {
-    if (theToForce
-     || !myIsImmediateDrawn)
-    {
-      myIsImmediateDrawn = Standard_False;
-      return;
-    }
+    theFBOPtr->BindBuffer (GetGlContext());
+  }
+  else
+  {
+  #if !defined(GL_ES_VERSION_2_0)
+    glGetIntegerv (GL_READ_BUFFER, &aReadBufferPrev);
+    GLint aDrawBufferPrev = GL_BACK;
+    glGetIntegerv (GL_DRAW_BUFFER, &aDrawBufferPrev);
+    glReadBuffer (aDrawBufferPrev);
+  #endif
+  }
 
-    if (myBackBufferRestored
-     && isDoubleBuffer)
-    {
-      copyBackToFront();
-      glFlush();
-    }
-    else
-    {
-      Redraw (theCView, theCUnderLayer, theCOverLayer);
-    }
-    return;
+  // setup alignment
+  const GLint anAligment   = Min (GLint(theImage.MaxRowAligmentBytes()), 8); // limit to 8 bytes for OpenGL
+  glPixelStorei (GL_PACK_ALIGNMENT, anAligment);
+  bool isBatchCopy = !theImage.IsTopDown();
+
+  const GLint   anExtraBytes       = GLint(theImage.RowExtraBytes());
+  GLint         aPixelsWidth       = GLint(theImage.SizeRowBytes() / theImage.SizePixelBytes());
+  Standard_Size aSizeRowBytesEstim = getAligned (theImage.SizePixelBytes() * aPixelsWidth, anAligment);
+  if (anExtraBytes < anAligment)
+  {
+    aPixelsWidth = 0;
+  }
+  else if (aSizeRowBytesEstim != theImage.SizeRowBytes())
+  {
+    aPixelsWidth = 0;
+    isBatchCopy  = false;
+  }
+#if !defined(GL_ES_VERSION_2_0)
+  glPixelStorei (GL_PACK_ROW_LENGTH, aPixelsWidth);
+#else
+  if (aPixelsWidth != 0)
+  {
+    isBatchCopy = false;
   }
+#endif
 
-  if (isDoubleBuffer && myTransientDrawToFront)
+  if (!isBatchCopy)
   {
-    if (!myBackBufferRestored)
+    // copy row by row
+    for (Standard_Size aRow = 0; aRow < theImage.SizeY(); ++aRow)
     {
-      Redraw (theCView, theCUnderLayer, theCOverLayer);
-      return;
+      // Image_PixMap rows indexation always starts from the upper corner
+      // while order in memory depends on the flag and processed by ChangeRow() method
+      glReadPixels (0, GLint(theImage.SizeY() - aRow - 1), GLsizei (theImage.SizeX()), 1, aFormat, aType, theImage.ChangeRow (aRow));
     }
-    copyBackToFront();
-    MakeFrontBufCurrent();
   }
   else
   {
-    myBackBufferRestored = Standard_False;
+    glReadPixels (0, 0, GLsizei (theImage.SizeX()), GLsizei (theImage.SizeY()), aFormat, aType, theImage.ChangeData());
   }
-  myIsImmediateDrawn = Standard_True;
 
-  NamedStatus |= OPENGL_NS_IMMEDIATE;
-  ///glDisable (GL_LIGHTING);
-  glDisable (GL_DEPTH_TEST);
+  glPixelStorei (GL_PACK_ALIGNMENT,  1);
+#if !defined(GL_ES_VERSION_2_0)
+  glPixelStorei (GL_PACK_ROW_LENGTH, 0);
+#endif
 
-  Handle(OpenGl_Workspace) aWS (this);
-  for (OpenGl_SequenceOfStructure::Iterator anIter (myView->ImmediateStructures());
-       anIter.More(); anIter.Next())
+  if (theFBOPtr != NULL && theFBOPtr->IsValid())
   {
-    const OpenGl_Structure* aStructure = anIter.Value();
-    aStructure->Render (aWS);
+    theFBOPtr->UnbindBuffer (GetGlContext());
   }
+  else
+  {
+  #if !defined(GL_ES_VERSION_2_0)
+    glReadBuffer (aReadBufferPrev);
+  #endif
+  }
+  return Standard_True;
+}
 
-  NamedStatus &= ~OPENGL_NS_IMMEDIATE;
-
-  if (isDoubleBuffer && myTransientDrawToFront)
+// =======================================================================
+// function : CanRender
+// purpose  :
+// =======================================================================
+Standard_Boolean OpenGl_RaytraceFilter::CanRender (const OpenGl_Element* theElement)
+{
+  Standard_Boolean aPrevFilterResult = Standard_True;
+  if (!myPrevRenderFilter.IsNull())
   {
-    glFlush();
-    MakeBackBufCurrent();
+    aPrevFilterResult = myPrevRenderFilter->CanRender (theElement);
   }
+  return aPrevFilterResult &&
+    !OpenGl_Raytrace::IsRaytracedElement (theElement);
 }