0027925: Visualization - implement order-independent transparency algorithm within...
[occt.git] / src / OpenGl / OpenGl_Workspace.cxx
index 237ece8..7ec727d 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_ArbFBO.hxx>
-
-#include <InterfaceGraphic.hxx>
+#include <OpenGl_Workspace.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_ShaderManager.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>
+#include <NCollection_AlignedAllocator.hxx>
+
+IMPLEMENT_STANDARD_RTTIEXT(OpenGl_Workspace,Standard_Transient)
+IMPLEMENT_STANDARD_RTTIEXT(OpenGl_RaytraceFilter,OpenGl_RenderFilter)
+
+#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 } };
-  static const OpenGl_Vec4 THE_BLACK_COLOR      (0.0f, 0.0f, 0.0f, 1.0f);
+  static const OpenGl_Vec4 THE_WHITE_COLOR (1.0f, 1.0f, 1.0f, 1.0f);
+  static const OpenGl_Vec4 THE_BLACK_COLOR (0.0f, 0.0f, 0.0f, 1.0f);
 
   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 =
-  {
-    16, Graphic3d_HTA_LEFT, Graphic3d_VTA_BOTTOM
-  };
-
   static const OpenGl_Matrix myDefaultMatrix =
   {
     {{ 1.0F, 0.0F, 0.0F, 0.0F },
@@ -65,22 +66,22 @@ namespace
      { 0.0F, 0.0F, 0.0F, 1.0F }}
   };
 
-};
+}
 
 // =======================================================================
 // function : Init
 // purpose  :
 // =======================================================================
-void OpenGl_Material::Init (const OPENGL_SURF_PROP& theProp)
+void OpenGl_Material::Init (const Graphic3d_MaterialAspect& theMat,
+                            const Quantity_Color&           theInteriorColor)
 {
+  const bool isPhysic = theMat.MaterialType (Graphic3d_MATERIAL_PHYSIC);
+
   // ambient component
-  if (theProp.color_mask & OPENGL_AMBIENT_MASK)
+  if (theMat.ReflectionMode (Graphic3d_TOR_AMBIENT))
   {
-    const float* aSrcAmb = theProp.isphysic ? theProp.ambcol.rgb : theProp.matcol.rgb;
-    Ambient = OpenGl_Vec4 (aSrcAmb[0] * theProp.amb,
-                           aSrcAmb[1] * theProp.amb,
-                           aSrcAmb[2] * theProp.amb,
-                           1.0f);
+    const OpenGl_Vec3& aSrcAmb = isPhysic ? theMat.AmbientColor() : theInteriorColor;
+    Ambient = OpenGl_Vec4 (aSrcAmb * theMat.Ambient(), 1.0f);
   }
   else
   {
@@ -88,13 +89,10 @@ void OpenGl_Material::Init (const OPENGL_SURF_PROP& theProp)
   }
 
   // diffusion component
-  if (theProp.color_mask & OPENGL_DIFFUSE_MASK)
+  if (theMat.ReflectionMode (Graphic3d_TOR_DIFFUSE))
   {
-    const float* aSrcDif = theProp.isphysic ? theProp.difcol.rgb : theProp.matcol.rgb;
-    Diffuse = OpenGl_Vec4 (aSrcDif[0] * theProp.diff,
-                           aSrcDif[1] * theProp.diff,
-                           aSrcDif[2] * theProp.diff,
-                           1.0f);
+    const OpenGl_Vec3& aSrcDif = isPhysic ? theMat.DiffuseColor() : theInteriorColor;
+    Diffuse = OpenGl_Vec4 (aSrcDif * theMat.Diffuse(), 1.0f);
   }
   else
   {
@@ -102,13 +100,10 @@ void OpenGl_Material::Init (const OPENGL_SURF_PROP& theProp)
   }
 
   // specular component
-  if (theProp.color_mask & OPENGL_SPECULAR_MASK)
+  if (theMat.ReflectionMode (Graphic3d_TOR_SPECULAR))
   {
-    const float* aSrcSpe = theProp.isphysic ? theProp.speccol.rgb : THE_WHITE_COLOR.rgb;
-    Specular = OpenGl_Vec4 (aSrcSpe[0] * theProp.spec,
-                            aSrcSpe[1] * theProp.spec,
-                            aSrcSpe[2] * theProp.spec,
-                            1.0f);
+    const OpenGl_Vec3& aSrcSpe = isPhysic ? (const OpenGl_Vec3& )theMat.SpecularColor() : THE_WHITE_COLOR.rgb();
+    Specular = OpenGl_Vec4 (aSrcSpe * theMat.Specular(), 1.0f);
   }
   else
   {
@@ -116,145 +111,69 @@ void OpenGl_Material::Init (const OPENGL_SURF_PROP& theProp)
   }
 
   // emission component
-  if (theProp.color_mask & OPENGL_EMISSIVE_MASK)
+  if (theMat.ReflectionMode (Graphic3d_TOR_EMISSION))
   {
-    const float* aSrcEms = theProp.isphysic ? theProp.emscol.rgb : theProp.matcol.rgb;
-    Emission = OpenGl_Vec4 (aSrcEms[0] * theProp.emsv,
-                            aSrcEms[1] * theProp.emsv,
-                            aSrcEms[2] * theProp.emsv,
-                            1.0f);
+    const OpenGl_Vec3& aSrcEms = isPhysic ? theMat.EmissiveColor() : theInteriorColor;
+    Emission = OpenGl_Vec4 (aSrcEms * theMat.Emissive(), 1.0f);
   }
   else
   {
     Emission = THE_BLACK_COLOR;
   }
 
-  ChangeShine()        = theProp.shine;
-  ChangeTransparency() = theProp.trans;
+  ChangeShine()        = 128.0f * theMat.Shininess();
+  ChangeTransparency() = 1.0f - theMat.Transparency();
 }
 
 // =======================================================================
 // 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),
-  HighlightColor (&THE_WHITE_COLOR),
+OpenGl_Workspace::OpenGl_Workspace (OpenGl_View* theView, const Handle(OpenGl_Window)& theWindow)
+: myView (theView),
+  myWindow (theWindow),
+  myGlContext (!theWindow.IsNull() ? theWindow->GetGlContext() : NULL),
+  myUseZBuffer    (Standard_True),
+  myUseDepthWrite (Standard_True),
   //
-  myHasFboBlit (Standard_True),
+  myAspectLineSet (&myDefaultAspectLine),
+  myAspectFaceSet (&myDefaultAspectFace),
+  myAspectMarkerSet (&myDefaultAspectMarker),
+  myAspectTextSet (&myDefaultAspectText),
   //
-  myViewId               (-1),
-  myAntiAliasingMode     (3),
-  myTransientDrawToFront (Standard_True),
-  myBackBufferRestored   (Standard_False),
-  myIsImmediateDrawn     (Standard_False),
-  myUseZBuffer (Standard_False),
-  myUseDepthTest (Standard_True),
-  myUseGLLight (Standard_True),
-  myIsCullingEnabled (Standard_False),
-  myFrameCounter (0),
-  //
-  AspectLine_set (&myDefaultAspectLine),
-  AspectLine_applied (NULL),
-  AspectFace_set (&myDefaultAspectFace),
-  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)
+  myToAllowFaceCulling (false),
+  myModelViewMatrix (myDefaultMatrix)
 {
-  myGlContext->core11fwd->glPixelStorei (GL_UNPACK_ALIGNMENT, 1);
-  myMainSceneFbos[0]      = new OpenGl_FrameBuffer();
-  myMainSceneFbos[1]      = new OpenGl_FrameBuffer();
-  myImmediateSceneFbos[0] = new OpenGl_FrameBuffer();
-  myImmediateSceneFbos[1] = new OpenGl_FrameBuffer();
-
-  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);
-  }
-
-  // General initialization of the context
-
-#if !defined(GL_ES_VERSION_2_0)
-  if (myGlContext->core11 != NULL)
+  if (!myGlContext.IsNull() && myGlContext->MakeCurrent())
   {
-    // 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);
+    myGlContext->core11fwd->glPixelStorei (GL_UNPACK_ALIGNMENT, 1);
 
-    // 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
-
-  // AA mode
-  const char* anAaEnv = ::getenv ("CALL_OPENGL_ANTIALIASING_MODE");
-  if (anAaEnv != NULL)
-  {
-    int v;
-    if (sscanf (anAaEnv, "%d", &v) > 0) myAntiAliasingMode = v;
-  }
-}
-
-// =======================================================================
-// function : SetImmediateModeDrawToFront
-// purpose  :
-// =======================================================================
-Standard_Boolean OpenGl_Workspace::SetImmediateModeDrawToFront (const Standard_Boolean theDrawToFrontBuffer)
-{
-  const Standard_Boolean aPrevMode = myTransientDrawToFront;
-  myTransientDrawToFront = theDrawToFrontBuffer;
-  return aPrevMode;
-}
+    // General initialization of the context
+  #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);
 
-inline void nullifyGlResource (Handle(OpenGl_Resource)&      theResource,
-                               const Handle(OpenGl_Context)& theCtx)
-{
-  if (!theResource.IsNull())
-  {
-    theResource->Release (theCtx.operator->());
-    theResource.Nullify();
-  }
-}
+      // Optimisation pour le Fog et l'antialiasing
+      glHint (GL_FOG_HINT,            GL_FASTEST);
+      glHint (GL_POINT_SMOOTH_HINT,   GL_FASTEST);
+    }
 
-// =======================================================================
-// function : ~OpenGl_Workspace
-// purpose  :
-// =======================================================================
-OpenGl_Workspace::~OpenGl_Workspace()
-{
-  if (!myLineAttribs.IsNull())
-  {
-    myLineAttribs.Nullify();
-    myGlContext->ReleaseResource ("OpenGl_LineAttributes", Standard_True);
+    glHint (GL_LINE_SMOOTH_HINT,    GL_FASTEST);
+    glHint (GL_POLYGON_SMOOTH_HINT, GL_FASTEST);
+  #endif
   }
 
-  nullifyGlResource (myMainSceneFbos[0],      myGlContext);
-  nullifyGlResource (myMainSceneFbos[1],      myGlContext);
-  nullifyGlResource (myImmediateSceneFbos[0], myGlContext);
-  nullifyGlResource (myImmediateSceneFbos[1], myGlContext);
+  myDefaultCappingAlgoFilter = new OpenGl_CappingAlgoFilter();
 
-  myFullScreenQuad.Release (myGlContext.operator->());
+  myNoneCulling .Aspect()->SetSuppressBackFaces (false);
+  myNoneCulling .Aspect()->SetDrawEdges (false);
+  myFrontCulling.Aspect()->SetSuppressBackFaces (true);
+  myFrontCulling.Aspect()->SetDrawEdges (false);
 }
 
 // =======================================================================
@@ -263,14 +182,23 @@ 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;
 
   ResetAppliedAspect();
 
+  // reset state for safety
+  myGlContext->BindProgram (Handle(OpenGl_ShaderProgram)());
+  if (myGlContext->core20fwd != NULL)
+  {
+    myGlContext->core20fwd->glUseProgram (OpenGl_ShaderProgram::NO_PROGRAM);
+  }
+  myGlContext->ShaderManager()->PushState (Handle(OpenGl_ShaderProgram)());
   return Standard_True;
 }
 
@@ -282,25 +210,23 @@ void OpenGl_Workspace::ResetAppliedAspect()
 {
   myGlContext->BindDefaultVao();
 
-  NamedStatus           = !myTextureBound.IsNull() ? OPENGL_NS_TEXTURE : 0;
-  HighlightColor        = &THE_WHITE_COLOR;
-  AspectLine_set        = &myDefaultAspectLine;
-  AspectLine_applied    = NULL;
-  AspectFace_set        = &myDefaultAspectFace;
-  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;
-
-  AspectLine(Standard_True);
-  AspectFace(Standard_True);
-  AspectMarker(Standard_True);
-  AspectText(Standard_True);
+  myHighlightStyle.Nullify();
+  myToAllowFaceCulling  = false;
+  myAspectLineSet       = &myDefaultAspectLine;
+  myAspectFaceSet       = &myDefaultAspectFace;
+  myAspectFaceApplied.Nullify();
+  myAspectMarkerSet     = &myDefaultAspectMarker;
+  myAspectMarkerApplied.Nullify();
+  myAspectTextSet       = &myDefaultAspectText;
+  myPolygonOffsetApplied= Graphic3d_PolygonOffset();
+
+  ApplyAspectLine();
+  ApplyAspectFace();
+  ApplyAspectMarker();
+  ApplyAspectText();
+
+  myGlContext->SetTypeOfLine (myDefaultAspectLine.Aspect()->Type());
+  myGlContext->SetLineWidth  (myDefaultAspectLine.Aspect()->Width());
 }
 
 // =======================================================================
@@ -390,21 +316,8 @@ void OpenGl_Workspace::setTextureParams (Handle(OpenGl_Texture)&
   }
 
 #if !defined(GL_ES_VERSION_2_0)
-  GLint aMatrixMode = GL_TEXTURE;
   if (myGlContext->core11 != NULL)
   {
-    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);
-
     GLint anEnvMode = GL_MODULATE; // lighting mode
     if (!aParams->IsModulate())
     {
@@ -461,12 +374,11 @@ void OpenGl_Workspace::setTextureParams (Handle(OpenGl_Texture)&
       }
       case Graphic3d_TOTM_SPRITE:
       {
-        if (GetGlContext()->core20fwd != NULL)
+        if (myGlContext->core20fwd != NULL)
         {
           glEnable  (GL_POINT_SPRITE);
           glTexEnvi (GL_POINT_SPRITE, GL_COORD_REPLACE, GL_TRUE);
           anEnvMode = GL_REPLACE;
-          GetGlContext()->core15->glPointParameteri (GL_POINT_SPRITE_COORD_ORIGIN, GL_LOWER_LEFT);
         }
         break;
       }
@@ -617,12 +529,6 @@ void OpenGl_Workspace::setTextureParams (Handle(OpenGl_Texture)&
     default: break;
   }
 
-#if !defined(GL_ES_VERSION_2_0)
-  if (myGlContext->core11 != NULL)
-  {
-    glMatrixMode (aMatrixMode); // turn back active matrix
-  }
-#endif
   theTexture->SetParams (aParams);
 }
 
@@ -663,800 +569,551 @@ Handle(OpenGl_Texture) OpenGl_Workspace::EnableTexture (const Handle(OpenGl_Text
 }
 
 // =======================================================================
-// function : bindDefaultFbo
+// function : SetAspectLine
 // purpose  :
 // =======================================================================
-void OpenGl_Workspace::bindDefaultFbo (OpenGl_FrameBuffer* theCustomFbo)
+const OpenGl_AspectLine* OpenGl_Workspace::SetAspectLine (const OpenGl_AspectLine* theAspect)
 {
-  OpenGl_FrameBuffer* anFbo = (theCustomFbo != NULL && theCustomFbo->IsValid())
-                            ?  theCustomFbo
-                            : (!myGlContext->DefaultFrameBuffer().IsNull()
-                             && myGlContext->DefaultFrameBuffer()->IsValid()
-                              ? myGlContext->DefaultFrameBuffer().operator->()
-                              : NULL);
-  if (anFbo != NULL)
-  {
-    anFbo->BindBuffer (myGlContext);
-  }
-  else
-  {
-  #if !defined(GL_ES_VERSION_2_0)
-    myGlContext->SetReadDrawBuffer (GL_BACK);
-  #else
-    if (myGlContext->arbFBO != NULL)
-    {
-      myGlContext->arbFBO->glBindFramebuffer (GL_FRAMEBUFFER, OpenGl_FrameBuffer::NO_FRAMEBUFFER);
-    }
-  #endif
-  }
-  myGlContext->core11fwd->glViewport (0, 0, myWidth, myHeight);
+  const OpenGl_AspectLine* aPrevAspectLine = myAspectLineSet;
+  myAspectLineSet = theAspect;
+  return aPrevAspectLine;
 }
 
 // =======================================================================
-// function : blitBuffers
+// function : SetAspectFace
 // purpose  :
 // =======================================================================
-bool OpenGl_Workspace::blitBuffers (OpenGl_FrameBuffer* theReadFbo,
-                                    OpenGl_FrameBuffer* theDrawFbo)
+const OpenGl_AspectFace * OpenGl_Workspace::SetAspectFace (const OpenGl_AspectFace* theAspect)
 {
-  if (theReadFbo == NULL)
-  {
-    return false;
-  }
-
-  // clear destination before blitting
-  if (theDrawFbo != NULL
-  &&  theDrawFbo->IsValid())
-  {
-    theDrawFbo->BindBuffer (myGlContext);
-  }
-  else
-  {
-    myGlContext->arbFBO->glBindFramebuffer (GL_FRAMEBUFFER, OpenGl_FrameBuffer::NO_FRAMEBUFFER);
-  }
-#if !defined(GL_ES_VERSION_2_0)
-  myGlContext->core20fwd->glClearDepth  (1.0);
-#else
-  myGlContext->core20fwd->glClearDepthf (1.0f);
-#endif
-  myGlContext->core20fwd->glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
-
-/*#if !defined(GL_ES_VERSION_2_0)
-  if (myGlContext->arbFBOBlit != NULL)
-  {
-    theReadFbo->BindReadBuffer (myGlContext);
-    if (theDrawFbo != NULL
-     && theDrawFbo->IsValid())
-    {
-      theDrawFbo->BindDrawBuffer (myGlContext);
-    }
-    else
-    {
-      myGlContext->arbFBO->glBindFramebuffer (GL_DRAW_FRAMEBUFFER, OpenGl_FrameBuffer::NO_FRAMEBUFFER);
-    }
-    // we don't copy stencil buffer here... does it matter for performance?
-    myGlContext->arbFBOBlit->glBlitFramebuffer (0, 0, theReadFbo->GetVPSizeX(), theReadFbo->GetVPSizeY(),
-                                                0, 0, theReadFbo->GetVPSizeX(), theReadFbo->GetVPSizeY(),
-                                                GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT, GL_NEAREST);
-
-    if (theDrawFbo != NULL
-      && theDrawFbo->IsValid())
-    {
-      theDrawFbo->BindBuffer (myGlContext);
-    }
-    else
-    {
-      myGlContext->arbFBO->glBindFramebuffer (GL_FRAMEBUFFER, OpenGl_FrameBuffer::NO_FRAMEBUFFER);
-    }
-  }
-  else
-#endif*/
-  {
-    myGlContext->core20fwd->glDepthFunc (GL_ALWAYS);
-    myGlContext->core20fwd->glDepthMask (GL_TRUE);
-    myGlContext->core20fwd->glEnable (GL_DEPTH_TEST);
-
-    DisableTexture();
-    if (!myFullScreenQuad.IsValid())
-    {
-      OpenGl_Vec4 aQuad[4] =
-      {
-        OpenGl_Vec4( 1.0f, -1.0f, 1.0f, 0.0f),
-        OpenGl_Vec4( 1.0f,  1.0f, 1.0f, 1.0f),
-        OpenGl_Vec4(-1.0f, -1.0f, 0.0f, 0.0f),
-        OpenGl_Vec4(-1.0f,  1.0f, 0.0f, 1.0f)
-      };
-      myFullScreenQuad.Init (myGlContext, 4, 4, aQuad[0].GetData());
-    }
-
-    const Handle(OpenGl_ShaderManager)& aManager = myGlContext->ShaderManager();
-    if (myFullScreenQuad.IsValid()
-     && aManager->BindFboBlitProgram())
-    {
-      theReadFbo->ColorTexture()       ->Bind   (myGlContext, GL_TEXTURE0 + 0);
-      theReadFbo->DepthStencilTexture()->Bind   (myGlContext, GL_TEXTURE0 + 1);
-      myFullScreenQuad.BindVertexAttrib (myGlContext, 0);
-
-      myGlContext->core20fwd->glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
-
-      myFullScreenQuad.UnbindVertexAttrib (myGlContext, 0);
-      theReadFbo->DepthStencilTexture()->Unbind (myGlContext, GL_TEXTURE0 + 1);
-      theReadFbo->ColorTexture()       ->Unbind (myGlContext, GL_TEXTURE0 + 0);
-    }
-    else
-    {
-      TCollection_ExtendedString aMsg = TCollection_ExtendedString()
-        + "Error! FBO blitting has failed";
-      myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
-                                GL_DEBUG_TYPE_ERROR_ARB,
-                                0,
-                                GL_DEBUG_SEVERITY_HIGH_ARB,
-                                aMsg);
-      myHasFboBlit = Standard_False;
-      theReadFbo->Release (myGlContext.operator->());
-      return true;
-    }
-  }
-  return true;
+  const OpenGl_AspectFace* aPrevAspectFace = myAspectFaceSet;
+  myAspectFaceSet = theAspect;
+  return aPrevAspectFace;
 }
 
 // =======================================================================
-// function : drawStereoPair
+// function : SetAspectMarker
 // purpose  :
 // =======================================================================
-void OpenGl_Workspace::drawStereoPair()
+const OpenGl_AspectMarker* OpenGl_Workspace::SetAspectMarker (const OpenGl_AspectMarker* theAspect)
 {
-  OpenGl_FrameBuffer* aPair[2] =
-  {
-    myImmediateSceneFbos[0]->IsValid() ? myImmediateSceneFbos[0].operator->() : NULL,
-    myImmediateSceneFbos[1]->IsValid() ? myImmediateSceneFbos[1].operator->() : NULL
-  };
-  if (aPair[0] == NULL
-   || aPair[1] == NULL)
-  {
-    aPair[0] = myMainSceneFbos[0]->IsValid() ? myMainSceneFbos[0].operator->() : NULL;
-    aPair[1] = myMainSceneFbos[1]->IsValid() ? myMainSceneFbos[1].operator->() : NULL;
-  }
-
-  if (aPair[0] == NULL
-   || aPair[1] == NULL)
-  {
-    return;
-  }
-
-  myGlContext->core20fwd->glDepthFunc (GL_ALWAYS);
-  myGlContext->core20fwd->glDepthMask (GL_TRUE);
-  myGlContext->core20fwd->glEnable (GL_DEPTH_TEST);
-
-  DisableTexture();
-  if (!myFullScreenQuad.IsValid())
-  {
-    OpenGl_Vec4 aQuad[4] =
-    {
-      OpenGl_Vec4( 1.0f, -1.0f, 1.0f, 0.0f),
-      OpenGl_Vec4( 1.0f,  1.0f, 1.0f, 1.0f),
-      OpenGl_Vec4(-1.0f, -1.0f, 0.0f, 0.0f),
-      OpenGl_Vec4(-1.0f,  1.0f, 0.0f, 1.0f)
-    };
-    myFullScreenQuad.Init (myGlContext, 4, 4, aQuad[0].GetData());
-  }
-
-  const Handle(OpenGl_ShaderManager)& aManager = myGlContext->ShaderManager();
-  if (myFullScreenQuad.IsValid()
-   && aManager->BindAnaglyphProgram())
-  {
-    aPair[0]->ColorTexture()->Bind (myGlContext, GL_TEXTURE0 + 0);
-    aPair[1]->ColorTexture()->Bind (myGlContext, GL_TEXTURE0 + 1);
-    myFullScreenQuad.BindVertexAttrib (myGlContext, 0);
-
-    myGlContext->core20fwd->glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
-
-    myFullScreenQuad.UnbindVertexAttrib (myGlContext, 0);
-    aPair[1]->ColorTexture()->Unbind (myGlContext, GL_TEXTURE0 + 1);
-    aPair[0]->ColorTexture()->Unbind (myGlContext, GL_TEXTURE0 + 0);
-  }
-  else
-  {
-    TCollection_ExtendedString aMsg = TCollection_ExtendedString()
-      + "Error! Anaglyph has failed";
-    myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
-                              GL_DEBUG_TYPE_ERROR_ARB,
-                              0,
-                              GL_DEBUG_SEVERITY_HIGH_ARB,
-                              aMsg);
-  }
+  const OpenGl_AspectMarker* aPrevAspectMarker = myAspectMarkerSet;
+  myAspectMarkerSet = theAspect;
+  return aPrevAspectMarker;
 }
 
 // =======================================================================
-// function : Redraw
+// function : SetAspectText
 // purpose  :
 // =======================================================================
-void OpenGl_Workspace::Redraw (const Graphic3d_CView& theCView,
-                               const Aspect_CLayer2d& theCUnderLayer,
-                               const Aspect_CLayer2d& theCOverLayer)
+const OpenGl_AspectText * OpenGl_Workspace::SetAspectText (const OpenGl_AspectText* theAspect)
 {
-  if (!Activate())
-  {
-    return;
-  }
-
-  ++myFrameCounter;
-  myIsCullingEnabled = theCView.IsCullingEnabled;
-
-  // release pending GL resources
-  myGlContext->ReleaseDelayed();
-
-  // fetch OpenGl context state
-  myGlContext->FetchState();
-
-  OpenGl_FrameBuffer* aFrameBuffer = (OpenGl_FrameBuffer* )theCView.ptrFBO;
-  bool toSwap = myGlContext->IsRender()
-            && !myGlContext->caps->buffersNoSwap
-            &&  aFrameBuffer == NULL;
-
-  Standard_Integer aSizeX = aFrameBuffer != NULL ? aFrameBuffer->GetVPSizeX() : myWidth;
-  Standard_Integer aSizeY = aFrameBuffer != NULL ? aFrameBuffer->GetVPSizeY() : myHeight;
-
-  if ( aFrameBuffer == NULL
-   && !myGlContext->DefaultFrameBuffer().IsNull()
-   &&  myGlContext->DefaultFrameBuffer()->IsValid())
-  {
-    aFrameBuffer = myGlContext->DefaultFrameBuffer().operator->();
-  }
+  const OpenGl_AspectText* aPrevAspectText = myAspectTextSet;
+  myAspectTextSet = theAspect;
+  return aPrevAspectText;
+}
 
-  if (myHasFboBlit
-   && myTransientDrawToFront)
+// =======================================================================
+// function : ApplyAspectFace
+// purpose  :
+// =======================================================================
+const OpenGl_AspectFace* OpenGl_Workspace::ApplyAspectFace()
+{
+  if (myView->BackfacingModel() == Graphic3d_TOBM_AUTOMATIC)
   {
-    if (myMainSceneFbos[0]->GetVPSizeX() != aSizeX
-     || myMainSceneFbos[0]->GetVPSizeY() != aSizeY)
+    // manage back face culling mode, disable culling when clipping is enabled
+    bool toSuppressBackFaces = myToAllowFaceCulling
+                            && myAspectFaceSet->Aspect()->ToSuppressBackFaces();
+    if (toSuppressBackFaces)
+    {
+      if (myGlContext->Clipping().IsClippingOrCappingOn()
+       || myAspectFaceSet->Aspect()->InteriorStyle() == Aspect_IS_HATCH)
+      {
+        toSuppressBackFaces = false;
+      }
+    }
+    if (toSuppressBackFaces)
     {
-      // prepare FBOs containing main scene
-      // for further blitting and rendering immediate presentations on top
-      if (myGlContext->core20fwd != NULL)
+      if ((float )myAspectFaceSet->Aspect()->FrontMaterial().Transparency() != 0.0f)
       {
-        myMainSceneFbos[0]->Init (myGlContext, aSizeX, aSizeY);
+        // disable culling in case of translucent shading aspect
+        toSuppressBackFaces = false;
       }
     }
+    myGlContext->SetCullBackFaces (toSuppressBackFaces);
   }
-  else
+
+  if (myAspectFaceSet->Aspect() == myAspectFaceApplied
+   && myHighlightStyle == myAspectFaceAppliedWithHL)
   {
-    myMainSceneFbos     [0]->Release (myGlContext.operator->());
-    myMainSceneFbos     [1]->Release (myGlContext.operator->());
-    myImmediateSceneFbos[0]->Release (myGlContext.operator->());
-    myImmediateSceneFbos[1]->Release (myGlContext.operator->());
-    myMainSceneFbos     [0]->ChangeViewport (0, 0);
-    myMainSceneFbos     [1]->ChangeViewport (0, 0);
-    myImmediateSceneFbos[0]->ChangeViewport (0, 0);
-    myImmediateSceneFbos[1]->ChangeViewport (0, 0);
+    return myAspectFaceSet;
   }
+  myAspectFaceAppliedWithHL = myHighlightStyle;
 
-  // draw entire frame using normal OpenGL pipeline
-  const Handle(Graphic3d_Camera)& aCamera      = myView->Camera();
-  Graphic3d_Camera::Projection    aProjectType = aCamera->ProjectionType();
-  if (aProjectType == Graphic3d_Camera::Projection_Stereo)
+#if !defined(GL_ES_VERSION_2_0)
+  const Aspect_InteriorStyle anIntstyle = myAspectFaceSet->Aspect()->InteriorStyle();
+  if (myAspectFaceApplied.IsNull()
+   || myAspectFaceApplied->InteriorStyle() != anIntstyle)
   {
-    if (aFrameBuffer != NULL
-    || !myGlContext->IsRender())
+    switch (anIntstyle)
     {
-      // implicitly switch to mono camera for image dump
-      aProjectType = Graphic3d_Camera::Projection_Perspective;
-    }
-    else if (myMainSceneFbos[0]->IsValid())
-    {
-      myMainSceneFbos[1]->InitLazy (myGlContext, aSizeX, aSizeY);
-      if (!myMainSceneFbos[1]->IsValid())
+      case Aspect_IS_EMPTY:
+      case Aspect_IS_HOLLOW:
+      {
+        myGlContext->SetPolygonMode (GL_LINE);
+        break;
+      }
+      case Aspect_IS_HATCH:
       {
-        // no enough memory?
-        aProjectType = Graphic3d_Camera::Projection_Perspective;
+        myGlContext->SetPolygonMode (GL_FILL);
+        myGlContext->SetPolygonHatchEnabled (true);
+        break;
       }
-      else if (!myGlContext->HasStereoBuffers())
+      case Aspect_IS_SOLID:
+      case Aspect_IS_HIDDENLINE:
       {
-        myImmediateSceneFbos[0]->InitLazy (myGlContext, aSizeX, aSizeY);
-        myImmediateSceneFbos[1]->InitLazy (myGlContext, aSizeX, aSizeY);
-        if (!myImmediateSceneFbos[0]->IsValid()
-         || !myImmediateSceneFbos[1]->IsValid())
-        {
-          aProjectType = Graphic3d_Camera::Projection_Perspective;
-        }
+        myGlContext->SetPolygonMode (GL_FILL);
+        myGlContext->SetPolygonHatchEnabled (false);
+        break;
+      }
+      case Aspect_IS_POINT:
+      {
+        myGlContext->SetPolygonMode (GL_POINT);
+        break;
       }
     }
   }
 
-  if (aProjectType == Graphic3d_Camera::Projection_Stereo)
+  if (anIntstyle == Aspect_IS_HATCH)
   {
-    OpenGl_FrameBuffer* aMainFbos[2] =
-    {
-      myMainSceneFbos[0]->IsValid() ? myMainSceneFbos[0].operator->() : NULL,
-      myMainSceneFbos[1]->IsValid() ? myMainSceneFbos[1].operator->() : NULL
-    };
-    OpenGl_FrameBuffer* anImmFbos[2] =
-    {
-      myImmediateSceneFbos[0]->IsValid() ? myImmediateSceneFbos[0].operator->() : NULL,
-      myImmediateSceneFbos[1]->IsValid() ? myImmediateSceneFbos[1].operator->() : NULL
-    };
-
-  #if !defined(GL_ES_VERSION_2_0)
-    myGlContext->SetReadDrawBuffer (GL_BACK_LEFT);
-  #endif
-    redraw1 (theCView, theCUnderLayer, theCOverLayer,
-             aMainFbos[0], Graphic3d_Camera::Projection_MonoLeftEye);
-    myBackBufferRestored = Standard_True;
-    myIsImmediateDrawn   = Standard_False;
-  #if !defined(GL_ES_VERSION_2_0)
-    myGlContext->SetReadDrawBuffer (GL_BACK_LEFT);
-  #endif
-    if (!redrawImmediate (theCView, theCOverLayer, theCUnderLayer, aMainFbos[0], aProjectType, anImmFbos[0]))
-    {
-      toSwap = false;
-    }
+    myGlContext->SetPolygonHatchStyle (myAspectFaceSet->Aspect()->HatchStyle());
+  }
+#endif
 
-  #if !defined(GL_ES_VERSION_2_0)
-    myGlContext->SetReadDrawBuffer (GL_BACK_RIGHT);
-  #endif
-    redraw1 (theCView, theCUnderLayer, theCOverLayer,
-             aMainFbos[1], Graphic3d_Camera::Projection_MonoRightEye);
-    myBackBufferRestored = Standard_True;
-    myIsImmediateDrawn   = Standard_False;
-    if (!redrawImmediate (theCView, theCOverLayer, theCUnderLayer, aMainFbos[1], aProjectType, anImmFbos[1]))
+  // Aspect_POM_None means: do not change current settings
+  if ((myAspectFaceSet->Aspect()->PolygonOffset().Mode & Aspect_POM_None) != Aspect_POM_None)
+  {
+    if (myPolygonOffsetApplied.Mode   != myAspectFaceSet->Aspect()->PolygonOffset().Mode
+     || myPolygonOffsetApplied.Factor != myAspectFaceSet->Aspect()->PolygonOffset().Factor
+     || myPolygonOffsetApplied.Units  != myAspectFaceSet->Aspect()->PolygonOffset().Units)
     {
-      toSwap = false;
+      SetPolygonOffset (myAspectFaceSet->Aspect()->PolygonOffset());
     }
+  }
 
-    if (anImmFbos[0] != NULL)
-    {
-      bindDefaultFbo (aFrameBuffer);
-      drawStereoPair();
-    }
+  // Case of hidden line
+  if (myAspectFaceSet->Aspect()->InteriorStyle() == Aspect_IS_HIDDENLINE)
+  {
+    // copy all values including line edge aspect
+    *myAspectFaceHl.Aspect().operator->() = *myAspectFaceSet->Aspect();
+    myAspectFaceHl.SetAspectEdge (myAspectFaceSet->AspectEdge());
+    myAspectFaceHl.Aspect()->SetInteriorColor (myView->BackgroundColor().GetRGB());
+    myAspectFaceHl.SetNoLighting (true);
+    myAspectFaceSet = &myAspectFaceHl;
   }
   else
   {
-    OpenGl_FrameBuffer* aMainFbo = myMainSceneFbos[0]->IsValid() ? myMainSceneFbos[0].operator->() : NULL;
-  #if !defined(GL_ES_VERSION_2_0)
-    if (aMainFbo     == NULL
-     && aFrameBuffer == NULL)
-    {
-      myGlContext->SetReadDrawBuffer (GL_BACK);
-    }
-  #endif
-    redraw1 (theCView, theCUnderLayer, theCOverLayer,
-             aMainFbo != NULL ? aMainFbo : aFrameBuffer, aProjectType);
-    myBackBufferRestored = Standard_True;
-    myIsImmediateDrawn   = Standard_False;
-    if (!redrawImmediate (theCView, theCOverLayer, theCUnderLayer, aMainFbo, aProjectType, aFrameBuffer))
-    {
-      toSwap = false;
-    }
+    myGlContext->SetShadingMaterial (myAspectFaceSet, myHighlightStyle);
   }
 
-#if defined(_WIN32) && defined(HAVE_VIDEOCAPTURE)
-  if (OpenGl_AVIWriter_AllowWriting (theCView.DefWindow.XWindow))
+  if (myAspectFaceSet->Aspect()->ToMapTexture())
   {
-    GLint params[4];
-    glGetIntegerv (GL_VIEWPORT, params);
-    int nWidth  = params[2] & ~0x7;
-    int nHeight = params[3] & ~0x7;
-
-    const int nBitsPerPixel = 24;
-    GLubyte* aDumpData = new GLubyte[nWidth * nHeight * nBitsPerPixel / 8];
-
-    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;
+    EnableTexture (myAspectFaceSet->TextureRes (myGlContext),
+                   myAspectFaceSet->TextureParams());
   }
-#endif
-
-  // bind default FBO
-  bindDefaultFbo();
-
-  // Swap the buffers
-  if (toSwap)
+  else
   {
-    GetGlContext()->SwapBuffers();
-    if (!myMainSceneFbos[0]->IsValid())
+    if (!myEnvironmentTexture.IsNull())
     {
-      myBackBufferRestored = Standard_False;
+      EnableTexture (myEnvironmentTexture,
+                     myEnvironmentTexture->GetParams());
+    }
+    else
+    {
+      DisableTexture();
     }
-  }
-  else
-  {
-    myGlContext->core11fwd->glFlush();
   }
 
-  // reset render mode state
-  myGlContext->FetchState();
+  myAspectFaceApplied = myAspectFaceSet->Aspect();
+  return myAspectFaceSet;
 }
 
-// =======================================================================
-// function : redraw1
-// purpose  :
-// =======================================================================
-void OpenGl_Workspace::redraw1 (const Graphic3d_CView&               theCView,
-                                const Aspect_CLayer2d&               theCUnderLayer,
-                                const Aspect_CLayer2d&               theCOverLayer,
-                                OpenGl_FrameBuffer*                  theReadDrawFbo,
-                                const Graphic3d_Camera::Projection   theProjection)
+//=======================================================================
+//function : SetPolygonOffset
+//purpose  :
+//=======================================================================
+void OpenGl_Workspace::SetPolygonOffset (const Graphic3d_PolygonOffset& theParams)
 {
-  if (myView.IsNull())
-  {
-    return;
-  }
+  myPolygonOffsetApplied = theParams;
 
-  if (theReadDrawFbo != NULL)
+  if ((theParams.Mode & Aspect_POM_Fill) == Aspect_POM_Fill)
   {
-    theReadDrawFbo->BindBuffer    (myGlContext);
-    theReadDrawFbo->SetupViewport (myGlContext);
+    glEnable (GL_POLYGON_OFFSET_FILL);
   }
   else
   {
-    myGlContext->core11fwd->glViewport (0, 0, myWidth, myHeight);
+    glDisable (GL_POLYGON_OFFSET_FILL);
   }
 
-  // request reset of material
-  NamedStatus |= OPENGL_NS_RESMAT;
-
-  GLbitfield toClear = GL_COLOR_BUFFER_BIT;
-  if (myUseZBuffer)
+#if !defined(GL_ES_VERSION_2_0)
+  if ((theParams.Mode & Aspect_POM_Line) == Aspect_POM_Line)
   {
-    glDepthFunc (GL_LEQUAL);
-    glDepthMask (GL_TRUE);
-    if (myUseDepthTest)
-    {
-      glEnable (GL_DEPTH_TEST);
-    }
-    else
-    {
-      glDisable (GL_DEPTH_TEST);
-    }
-
-  #if !defined(GL_ES_VERSION_2_0)
-    glClearDepth (1.0);
-  #else
-    glClearDepthf (1.0f);
-  #endif
-    toClear |= GL_DEPTH_BUFFER_BIT;
+    glEnable (GL_POLYGON_OFFSET_LINE);
   }
   else
   {
-    glDisable (GL_DEPTH_TEST);
+    glDisable (GL_POLYGON_OFFSET_LINE);
   }
 
-  if (NamedStatus & OPENGL_NS_WHITEBACK)
+  if ((theParams.Mode & Aspect_POM_Point) == Aspect_POM_Point)
   {
-    // set background to white
-    glClearColor (1.0f, 1.0f, 1.0f, 1.0f);
-    toClear |= GL_DEPTH_BUFFER_BIT;
+    glEnable (GL_POLYGON_OFFSET_POINT);
   }
   else
   {
-    glClearColor (myBgColor.rgb[0], myBgColor.rgb[1], myBgColor.rgb[2], 0.0f);
+    glDisable (GL_POLYGON_OFFSET_POINT);
   }
-
-  glClear (toClear);
-
-  Handle(OpenGl_Workspace) aWS (this);
-  myView->Render (myPrintContext, aWS, theReadDrawFbo, theProjection, theCView, theCUnderLayer, theCOverLayer, Standard_False);
+#endif
+  glPolygonOffset (theParams.Factor, theParams.Units);
 }
 
 // =======================================================================
-// function : copyBackToFront
+// function : ApplyAspectMarker
 // purpose  :
 // =======================================================================
-void OpenGl_Workspace::copyBackToFront()
+const OpenGl_AspectMarker* OpenGl_Workspace::ApplyAspectMarker()
 {
-#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));
-
-  myGlContext->WorldViewState.Push();
-  myGlContext->ProjectionState.Push();
-
-  myGlContext->WorldViewState.SetIdentity();
-  myGlContext->ProjectionState.SetCurrent (aProjectMat);
-
-  myGlContext->ApplyProjectionMatrix();
-  myGlContext->ApplyWorldViewMatrix();
-
-  DisableFeatures();
-
-  switch (myGlContext->DrawBuffer())
+  if (myAspectMarkerSet->Aspect() != myAspectMarkerApplied)
   {
-    case GL_BACK_LEFT:
-    {
-      myGlContext->SetReadBuffer (GL_BACK_LEFT);
-      myGlContext->SetDrawBuffer (GL_FRONT_LEFT);
-      break;
-    }
-    case GL_BACK_RIGHT:
+    if (myAspectMarkerApplied.IsNull()
+    || (myAspectMarkerSet->Aspect()->Scale() != myAspectMarkerApplied->Scale()))
     {
-      myGlContext->SetReadBuffer (GL_BACK_RIGHT);
-      myGlContext->SetDrawBuffer (GL_FRONT_RIGHT);
-      break;
-    }
-    default:
-    {
-      myGlContext->SetReadBuffer (GL_BACK);
-      myGlContext->SetDrawBuffer (GL_FRONT);
-      break;
+    #if !defined(GL_ES_VERSION_2_0)
+      glPointSize (myAspectMarkerSet->Aspect()->Scale());
+    #ifdef HAVE_GL2PS
+      gl2psPointSize (myAspectMarkerSet->Aspect()->Scale());
+    #endif
+    #endif
     }
+    myAspectMarkerApplied = myAspectMarkerSet->Aspect();
   }
+  return myAspectMarkerSet;
+}
+
+// =======================================================================
+// function : Width
+// purpose  :
+// =======================================================================
+Standard_Integer OpenGl_Workspace::Width()  const
+{
+  return !myView->GlWindow().IsNull() ? myView->GlWindow()->Width() : 0;
+}
+
+// =======================================================================
+// function : Height
+// purpose  :
+// =======================================================================
+Standard_Integer OpenGl_Workspace::Height() const
+{
+  return !myView->GlWindow().IsNull() ? myView->GlWindow()->Height() : 0;
+}
 
-  glRasterPos2i (0, 0);
-  glCopyPixels  (0, 0, myWidth + 1, myHeight + 1, GL_COLOR);
-  //glCopyPixels  (0, 0, myWidth + 1, myHeight + 1, GL_DEPTH);
+// =======================================================================
+// function : IsCullingEnabled
+// purpose  :
+// =======================================================================
+Standard_Boolean OpenGl_Workspace::IsCullingEnabled() const
+{
+  return myView->IsCullingEnabled();
+}
 
-  EnableFeatures();
+// =======================================================================
+// function : FBOCreate
+// purpose  :
+// =======================================================================
+Handle(OpenGl_FrameBuffer) OpenGl_Workspace::FBOCreate (const Standard_Integer theWidth,
+                                                        const Standard_Integer theHeight)
+{
+  // activate OpenGL context
+  if (!Activate())
+    return Handle(OpenGl_FrameBuffer)();
 
-  myGlContext->WorldViewState.Pop();
-  myGlContext->ProjectionState.Pop();
-  myGlContext->ApplyProjectionMatrix();
+  DisableTexture();
 
-  // read/write from front buffer now
-  myGlContext->SetReadBuffer (myGlContext->DrawBuffer());
-#endif
-  myIsImmediateDrawn = Standard_False;
+  // create the FBO
+  const Handle(OpenGl_Context)& aCtx = GetGlContext();
+  Handle(OpenGl_FrameBuffer) aFrameBuffer = new OpenGl_FrameBuffer();
+  if (!aFrameBuffer->Init (aCtx, theWidth, theHeight, GL_RGBA8, GL_DEPTH24_STENCIL8, 0))
+  {
+    aFrameBuffer->Release (aCtx.operator->());
+    return Handle(OpenGl_FrameBuffer)();
+  }
+  return aFrameBuffer;
 }
 
 // =======================================================================
-// function : DisplayCallback
+// function : FBORelease
 // purpose  :
 // =======================================================================
-void OpenGl_Workspace::DisplayCallback (const Graphic3d_CView& theCView,
-                                        Standard_Integer       theReason)
+void OpenGl_Workspace::FBORelease (Handle(OpenGl_FrameBuffer)& theFbo)
 {
-  if (theCView.GDisplayCB == NULL)
+  // activate OpenGL context
+  if (!Activate()
+   || theFbo.IsNull())
   {
     return;
   }
 
-  Aspect_GraphicCallbackStruct aCallData;
-  aCallData.reason    = theReason;
-  aCallData.glContext = myGlContext;
-  aCallData.wsID      = theCView.WsId;
-  aCallData.viewID    = theCView.ViewId;
-  aCallData.IsCoreProfile = (myGlContext->core11 == NULL);
-  theCView.GDisplayCB (theCView.DefWindow.XWindow, theCView.GClientData, &aCallData);
+  theFbo->Release (GetGlContext().operator->());
+  theFbo.Nullify();
 }
 
 // =======================================================================
-// function : RedrawImmediate
+// function : getAligned
 // purpose  :
 // =======================================================================
-void OpenGl_Workspace::RedrawImmediate (const Graphic3d_CView& theCView,
-                                        const Aspect_CLayer2d& theCUnderLayer,
-                                        const Aspect_CLayer2d& theCOverLayer)
+inline Standard_Size getAligned (const Standard_Size theNumber,
+                                 const Standard_Size theAlignment)
 {
-  const Handle(Graphic3d_Camera)& aCamera      = myView->Camera();
-  Graphic3d_Camera::Projection    aProjectType = aCamera->ProjectionType();
-  OpenGl_FrameBuffer* aFrameBuffer = (OpenGl_FrameBuffer* )theCView.ptrFBO;
-  if ( aFrameBuffer == NULL
-   && !myGlContext->DefaultFrameBuffer().IsNull()
-   &&  myGlContext->DefaultFrameBuffer()->IsValid())
+  return theNumber + theAlignment - 1 - (theNumber - 1) % theAlignment;
+}
+
+template<typename T>
+inline void convertRowFromRgba (T* theRgbRow,
+                                const Image_ColorRGBA* theRgbaRow,
+                                const Standard_Size theWidth)
+{
+  for (Standard_Size aCol = 0; aCol < theWidth; ++aCol)
   {
-    aFrameBuffer = myGlContext->DefaultFrameBuffer().operator->();
+    const Image_ColorRGBA& anRgba = theRgbaRow[aCol];
+    T& anRgb = theRgbRow[aCol];
+    anRgb.r() = anRgba.r();
+    anRgb.g() = anRgba.g();
+    anRgb.b() = anRgba.b();
   }
+}
 
-  if (aProjectType == Graphic3d_Camera::Projection_Stereo)
+// =======================================================================
+// function : BufferDump
+// purpose  :
+// =======================================================================
+Standard_Boolean OpenGl_Workspace::BufferDump (const Handle(OpenGl_FrameBuffer)& theFbo,
+                                               Image_PixMap&                     theImage,
+                                               const Graphic3d_BufferType&       theBufferType)
+{
+  if (theImage.IsEmpty()
+  || !Activate())
   {
-    if (aFrameBuffer != NULL)
-    {
-      // implicitly switch to mono camera for image dump
-      aProjectType = Graphic3d_Camera::Projection_Perspective;
-    }
-    else if (myMainSceneFbos[0]->IsValid()
-         && !myMainSceneFbos[1]->IsValid())
-    {
-      aProjectType = Graphic3d_Camera::Projection_Perspective;
-    }
+    return Standard_False;
   }
 
-  if (!myTransientDrawToFront
-   || !myBackBufferRestored
-   || (myGlContext->caps->buffersNoSwap && !myMainSceneFbos[0]->IsValid()))
+  GLenum aFormat = 0;
+  GLenum aType   = 0;
+  bool toSwapRgbaBgra = false;
+  bool toConvRgba2Rgb = false;
+  switch (theImage.Format())
   {
-    Redraw (theCView, theCUnderLayer, theCOverLayer);
-    return;
+  #if !defined(GL_ES_VERSION_2_0)
+    case Image_Format_Gray:
+      aFormat = GL_DEPTH_COMPONENT;
+      aType   = GL_UNSIGNED_BYTE;
+      break;
+    case Image_Format_GrayF:
+      aFormat = GL_DEPTH_COMPONENT;
+      aType   = GL_FLOAT;
+      break;
+    case Image_Format_RGB:
+      aFormat = GL_RGB;
+      aType   = GL_UNSIGNED_BYTE;
+      break;
+    case Image_Format_BGR:
+      aFormat = GL_BGR;
+      aType   = GL_UNSIGNED_BYTE;
+      break;
+    case Image_Format_BGRA:
+    case Image_Format_BGR32:
+      aFormat = GL_BGRA;
+      aType   = GL_UNSIGNED_BYTE;
+      break;
+    case Image_Format_BGRF:
+      aFormat = GL_BGR;
+      aType   = GL_FLOAT;
+      break;
+    case Image_Format_BGRAF:
+      aFormat = GL_BGRA;
+      aType   = GL_FLOAT;
+      break;
+  #else
+    case Image_Format_Gray:
+    case Image_Format_GrayF:
+    case Image_Format_BGRF:
+    case Image_Format_BGRAF:
+      return Standard_False;
+    case Image_Format_BGRA:
+    case Image_Format_BGR32:
+      aFormat = GL_RGBA;
+      aType   = GL_UNSIGNED_BYTE;
+      toSwapRgbaBgra = true;
+      break;
+    case Image_Format_BGR:
+    case Image_Format_RGB:
+      aFormat = GL_RGBA;
+      aType   = GL_UNSIGNED_BYTE;
+      toConvRgba2Rgb = true;
+      break;
+  #endif
+    case Image_Format_RGBA:
+    case Image_Format_RGB32:
+      aFormat = GL_RGBA;
+      aType   = GL_UNSIGNED_BYTE;
+      break;
+    case Image_Format_RGBF:
+      aFormat = GL_RGB;
+      aType   = GL_FLOAT;
+      break;
+    case Image_Format_RGBAF:
+      aFormat = GL_RGBA;
+      aType   = GL_FLOAT;
+      break;
+    case Image_Format_Alpha:
+    case Image_Format_AlphaF:
+      return Standard_False; // GL_ALPHA is no more supported in core context
+    case Image_Format_UNKNOWN:
+      return Standard_False;
   }
-  else if (!Activate())
+
+  if (aFormat == 0)
   {
-    return;
+    return Standard_False;
   }
 
-  bool toSwap = false;
-  if (aProjectType == Graphic3d_Camera::Projection_Stereo)
+#if !defined(GL_ES_VERSION_2_0)
+  GLint aReadBufferPrev = GL_BACK;
+  if (theBufferType == Graphic3d_BT_Depth
+   && aFormat != GL_DEPTH_COMPONENT)
   {
-    OpenGl_FrameBuffer* aMainFbos[2] =
-    {
-      myMainSceneFbos[0]->IsValid() ? myMainSceneFbos[0].operator->() : NULL,
-      myMainSceneFbos[1]->IsValid() ? myMainSceneFbos[1].operator->() : NULL
-    };
-    OpenGl_FrameBuffer* anImmFbos[2] =
-    {
-      myImmediateSceneFbos[0]->IsValid() ? myImmediateSceneFbos[0].operator->() : NULL,
-      myImmediateSceneFbos[1]->IsValid() ? myImmediateSceneFbos[1].operator->() : NULL
-    };
-
-    if (myGlContext->arbFBO != NULL)
-    {
-      myGlContext->arbFBO->glBindFramebuffer (GL_FRAMEBUFFER, OpenGl_FrameBuffer::NO_FRAMEBUFFER);
-    }
-  #if !defined(GL_ES_VERSION_2_0)
-    if (anImmFbos[0] == NULL)
-    {
-      myGlContext->SetReadDrawBuffer (GL_BACK_LEFT);
-    }
-  #endif
-    toSwap = redrawImmediate (theCView, theCUnderLayer, theCOverLayer,
-                              aMainFbos[0],
-                              Graphic3d_Camera::Projection_MonoLeftEye,
-                              anImmFbos[0],
-                              Standard_True) || toSwap;
+    return Standard_False;
+  }
+#else
+  (void )theBufferType;
+#endif
 
-    if (myGlContext->arbFBO != NULL)
-    {
-      myGlContext->arbFBO->glBindFramebuffer (GL_FRAMEBUFFER, OpenGl_FrameBuffer::NO_FRAMEBUFFER);
-    }
-  #if !defined(GL_ES_VERSION_2_0)
-    if (anImmFbos[1] == NULL)
-    {
-      myGlContext->SetReadDrawBuffer (GL_BACK_RIGHT);
-    }
-  #endif
-    toSwap = redrawImmediate (theCView, theCUnderLayer, theCOverLayer,
-                              aMainFbos[1],
-                              Graphic3d_Camera::Projection_MonoRightEye,
-                              anImmFbos[1],
-                              Standard_True) || toSwap;
-    if (anImmFbos[0] != NULL)
-    {
-      bindDefaultFbo (aFrameBuffer);
-      drawStereoPair();
-    }
+  // bind FBO if used
+  if (!theFbo.IsNull() && theFbo->IsValid())
+  {
+    theFbo->BindBuffer (GetGlContext());
   }
   else
   {
-    OpenGl_FrameBuffer* aMainFbo = myMainSceneFbos[0]->IsValid() ? myMainSceneFbos[0].operator->() : NULL;
   #if !defined(GL_ES_VERSION_2_0)
-    if (aMainFbo == NULL)
-    {
-      myGlContext->SetReadDrawBuffer (GL_BACK);
-    }
+    glGetIntegerv (GL_READ_BUFFER, &aReadBufferPrev);
+    GLint aDrawBufferPrev = GL_BACK;
+    glGetIntegerv (GL_DRAW_BUFFER, &aDrawBufferPrev);
+    glReadBuffer (aDrawBufferPrev);
   #endif
-    toSwap = redrawImmediate (theCView, theCUnderLayer, theCOverLayer,
-                              aMainFbo,
-                              aProjectType,
-                              aFrameBuffer,
-                              Standard_True) || toSwap;
   }
 
-  // bind default FBO
-  bindDefaultFbo();
+  // 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();
 
-  if (toSwap
-  && !myGlContext->caps->buffersNoSwap)
+  const GLint   anExtraBytes       = GLint(theImage.RowExtraBytes());
+  GLint         aPixelsWidth       = GLint(theImage.SizeRowBytes() / theImage.SizePixelBytes());
+  Standard_Size aSizeRowBytesEstim = getAligned (theImage.SizePixelBytes() * aPixelsWidth, anAligment);
+  if (anExtraBytes < anAligment)
   {
-    myGlContext->SwapBuffers();
+    aPixelsWidth = 0;
   }
-  else
+  else if (aSizeRowBytesEstim != theImage.SizeRowBytes())
   {
-    myGlContext->core11fwd->glFlush();
+    aPixelsWidth = 0;
+    isBatchCopy  = false;
   }
-}
-
-// =======================================================================
-// function : redrawImmediate
-// purpose  :
-// =======================================================================
-bool OpenGl_Workspace::redrawImmediate (const Graphic3d_CView& theCView,
-                                        const Aspect_CLayer2d& theCUnderLayer,
-                                        const Aspect_CLayer2d& theCOverLayer,
-                                        OpenGl_FrameBuffer*    theReadFbo,
-                                        const Graphic3d_Camera::Projection theProjection,
-                                        OpenGl_FrameBuffer*    theDrawFbo,
-                                        const Standard_Boolean theIsPartialUpdate)
-{
-  GLboolean toCopyBackToFront = GL_FALSE;
-  if (!myTransientDrawToFront)
+#if !defined(GL_ES_VERSION_2_0)
+  glPixelStorei (GL_PACK_ROW_LENGTH, aPixelsWidth);
+#else
+  if (aPixelsWidth != 0)
   {
-    myBackBufferRestored = Standard_False;
+    isBatchCopy = false;
   }
-  else if (theReadFbo != NULL
-        && theReadFbo->IsValid()
-        && myGlContext->IsRender())
+#endif
+  if (toConvRgba2Rgb)
   {
-    if (!blitBuffers (theReadFbo, theDrawFbo))
+    Handle(NCollection_BaseAllocator) anAlloc = new NCollection_AlignedAllocator (16);
+    const Standard_Size aRowSize = theImage.SizeX() * 4;
+    NCollection_Buffer aRowBuffer (anAlloc);
+    if (!aRowBuffer.Allocate (aRowSize))
     {
-      return true;
+      return Standard_False;
     }
-  }
-  else if (theDrawFbo == NULL)
-  {
-  #if !defined(GL_ES_VERSION_2_0)
-    myGlContext->core11fwd->glGetBooleanv (GL_DOUBLEBUFFER, &toCopyBackToFront);
-  #endif
-    if (toCopyBackToFront)
+
+    for (Standard_Size aRow = 0; aRow < theImage.SizeY(); ++aRow)
     {
-      if (!myView->HasImmediateStructures()
-       && !theIsPartialUpdate)
+      // 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, aRowBuffer.ChangeData());
+      const Image_ColorRGBA* aRowDataRgba = (const Image_ColorRGBA* )aRowBuffer.Data();
+      if (theImage.Format() == Image_Format_BGR)
+      {
+        convertRowFromRgba ((Image_ColorBGR* )theImage.ChangeRow (aRow), aRowDataRgba, theImage.SizeX());
+      }
+      else
       {
-        // prefer Swap Buffers within Redraw in compatibility mode (without FBO)
-        return true;
+        convertRowFromRgba ((Image_ColorRGB* )theImage.ChangeRow (aRow), aRowDataRgba, theImage.SizeX());
       }
-      copyBackToFront();
     }
-    else
+  }
+  else if (!isBatchCopy)
+  {
+    // copy row by row
+    for (Standard_Size aRow = 0; aRow < theImage.SizeY(); ++aRow)
     {
-      myBackBufferRestored = Standard_False;
+      // 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));
     }
   }
   else
   {
-    myBackBufferRestored = Standard_False;
+    glReadPixels (0, 0, GLsizei (theImage.SizeX()), GLsizei (theImage.SizeY()), aFormat, aType, theImage.ChangeData());
   }
-  myIsImmediateDrawn = Standard_True;
+  const bool hasErrors = myGlContext->ResetErrors (true);
 
-  Handle(OpenGl_Workspace) aWS (this);
+  glPixelStorei (GL_PACK_ALIGNMENT,  1);
+#if !defined(GL_ES_VERSION_2_0)
+  glPixelStorei (GL_PACK_ROW_LENGTH, 0);
+#endif
 
-  if (myUseZBuffer)
+  if (!theFbo.IsNull() && theFbo->IsValid())
   {
-    glDepthFunc (GL_LEQUAL);
-    glDepthMask (GL_TRUE);
-    if (myUseDepthTest)
-    {
-      glEnable (GL_DEPTH_TEST);
-    }
-    else
-    {
-      glDisable (GL_DEPTH_TEST);
-    }
-
-  #if !defined(GL_ES_VERSION_2_0)
-    glClearDepth (1.0);
-  #else
-    glClearDepthf (1.0f);
-  #endif
+    theFbo->UnbindBuffer (GetGlContext());
   }
   else
   {
-    glDisable (GL_DEPTH_TEST);
+  #if !defined(GL_ES_VERSION_2_0)
+    glReadBuffer (aReadBufferPrev);
+  #endif
   }
 
-  myView->Render (myPrintContext, aWS, theDrawFbo, theProjection,
-                  theCView, theCUnderLayer, theCOverLayer, Standard_True);
-  if (!myView->ImmediateStructures().IsEmpty())
+  if (toSwapRgbaBgra)
   {
-    glDisable (GL_DEPTH_TEST);
+    Image_PixMap::SwapRgbaBgra (theImage);
   }
-  for (OpenGl_SequenceOfStructure::Iterator anIter (myView->ImmediateStructures());
-       anIter.More(); anIter.Next())
-  {
-    const OpenGl_Structure* aStructure = anIter.Value();
-    if (!aStructure->IsVisible())
-    {
-      continue;
-    }
 
-    aStructure->Render (aWS);
-  }
-
-  return !toCopyBackToFront;
+  return !hasErrors;
 }
 
-IMPLEMENT_STANDARD_HANDLE (OpenGl_RaytraceFilter, OpenGl_RenderFilter)
-IMPLEMENT_STANDARD_RTTIEXT(OpenGl_RaytraceFilter, OpenGl_RenderFilter)
-
 // =======================================================================
-// function : CanRender
+// function : ShouldRender
 // purpose  :
 // =======================================================================
-Standard_Boolean OpenGl_RaytraceFilter::CanRender (const OpenGl_Element* theElement)
+Standard_Boolean OpenGl_RaytraceFilter::ShouldRender (const Handle(OpenGl_Workspace)& theWorkspace,
+                                                      const OpenGl_Element*           theElement)
 {
   Standard_Boolean aPrevFilterResult = Standard_True;
   if (!myPrevRenderFilter.IsNull())
   {
-    aPrevFilterResult = myPrevRenderFilter->CanRender (theElement);
+    aPrevFilterResult = myPrevRenderFilter->ShouldRender (theWorkspace, theElement);
   }
   return aPrevFilterResult &&
     !OpenGl_Raytrace::IsRaytracedElement (theElement);