0027606: Visualization - view is blocking when MSAA has been overridden in graphics...
[occt.git] / src / OpenGl / OpenGl_View.cxx
index 012af13..c054675 100644 (file)
 // Created on: 2011-09-20
 // Created by: Sergey ZERCHANINOV
-// Copyright (c) 2011-2012 OPEN CASCADE SAS
+// Copyright (c) 2011-2014 OPEN CASCADE SAS
 //
-// The content of this file is subject to the Open CASCADE Technology Public
-// License Version 6.5 (the "License"). You may not use the content of this file
-// except in compliance with the License. Please obtain a copy of the License
-// at http://www.opencascade.org and read it completely before using this file.
+// This file is part of Open CASCADE Technology software library.
 //
-// The Initial Developer of the Original Code is Open CASCADE S.A.S., having its
-// main offices at: 1, place des Freres Montgolfier, 78280 Guyancourt, France.
+// This library is free software; you can redistribute it and/or modify it under
+// the terms of the GNU Lesser General Public License version 2.1 as published
+// by the Free Software Foundation, with special exception defined in the file
+// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
+// distribution for complete text of the license and disclaimer of any warranty.
 //
-// The Original Code and all software distributed under the License is
-// distributed on an "AS IS" basis, without warranty of any kind, and the
-// Initial Developer hereby disclaims all such warranties, including without
-// limitation, any warranties of merchantability, fitness for a particular
-// purpose or non-infringement. Please see the License for the specific terms
-// and conditions governing the rights and limitations under the License.
-
-
-#include <OpenGl_GlCore11.hxx>
+// Alternatively, this file may be used under the terms of Open CASCADE
+// commercial license or contractual agreement.
 
 #include <OpenGl_View.hxx>
-#include <OpenGl_Context.hxx>
-#include <OpenGl_Workspace.hxx>
-#include <OpenGl_Display.hxx>
 
+#include <Aspect_RenderingContext.hxx>
+#include <Aspect_Window.hxx>
+#include <Graphic3d_AspectFillArea3d.hxx>
+#include <Graphic3d_Texture2Dmanual.hxx>
+#include <Graphic3d_TextureEnv.hxx>
+#include <Graphic3d_Mat4d.hxx>
+#include <NCollection_Mat4.hxx>
+#include <OpenGl_Context.hxx>
+#include <OpenGl_FrameBuffer.hxx>
+#include <OpenGl_GlCore11.hxx>
+#include <OpenGl_GraduatedTrihedron.hxx>
+#include <OpenGl_GraphicDriver.hxx>
+#include <OpenGl_ShaderManager.hxx>
 #include <OpenGl_Texture.hxx>
 #include <OpenGl_Trihedron.hxx>
-#include <OpenGl_GraduatedTrihedron.hxx>
-
-#include <OpenGl_transform_persistence.hxx>
-
-#include <Graphic3d_TextureEnv.hxx>
+#include <OpenGl_Window.hxx>
+#include <OpenGl_Workspace.hxx>
+#include <Standard_CLocaleSentry.hxx>
 
-#include <GL/glu.h> // gluUnProject()
+IMPLEMENT_STANDARD_RTTIEXT(OpenGl_View,Graphic3d_CView)
 
-IMPLEMENT_STANDARD_HANDLE(OpenGl_View,MMgt_TShared)
-IMPLEMENT_STANDARD_RTTIEXT(OpenGl_View,MMgt_TShared)
+#ifdef HAVE_GL2PS
+#include <gl2ps.h>
+#endif
 
 /*----------------------------------------------------------------------*/
 
-static const OPENGL_BG_TEXTURE myDefaultBgTexture = { 0, 0, 0, Aspect_FM_CENTERED };
-static const OPENGL_BG_GRADIENT myDefaultBgGradient = { {{ 0.F, 0.F, 0.F, 1.F }}, {{ 0.F, 0.F, 0.F, 1.F }}, Aspect_GFM_NONE };
-static const Tmatrix3 myDefaultMatrix = { { 1.F, 0.F, 0.F, 0.F }, { 0.F, 1.F, 0.F, 0.F }, { 0.F, 0.F, 1.F, 0.F }, { 0.F, 0.F, 0.F, 1.F } };
-static const OPENGL_ZCLIP myDefaultZClip = { { Standard_True, 0.F }, { Standard_True, 1.F } };
-static const OPENGL_EXTRA_REP myDefaultExtra =
-{
-  //vrp
-  { 0.F, 0.F, 0.F },
-  //vpn
-  { 0.F, 0.F, 1.F },
-  //vup
-  { 0.F, 1.F, 0.F },
-  //map
-  {
-    //window
-    { 0.F, 0.F, 1.F, 1.F },
-    //viewport
-    { 0.F, 0.F, 0.F, 1.F, 1.F, 1.F },
-    //proj
-    TelParallel,
-    //prp
-    { 0.F, 0.F, 0.F },
-    //vpd
-    0.F,
-    //fpd
-    0.F,
-    //bpd
-    -1.F
-  },
-  //scaleFactors
-  { 1.F, 1.F, 1.F }
-};
-
-static const OPENGL_FOG myDefaultFog = { Standard_False, 0.F, 1.F, { { 0.F, 0.F, 0.F, 1.F } } };
-static const TEL_TRANSFORM_PERSISTENCE myDefaultTransPers = { 0, 0.F, 0.F, 0.F };
+namespace
+{
+  static const OPENGL_ZCLIP myDefaultZClip = { { Standard_False, 0.F }, { Standard_False, 1.F } };
+  static const OPENGL_FOG   myDefaultFog   = { Standard_False, 0.F, 1.F, { { 0.F, 0.F, 0.F, 1.F } } };
+  static const TEL_COLOUR   myDefaultBg    = { { 0.F, 0.F, 0.F, 1.F } };
+}
 
-/*----------------------------------------------------------------------*/
+// =======================================================================
+// function : Constructor
+// purpose  :
+// =======================================================================
+OpenGl_View::OpenGl_View (const Handle(Graphic3d_StructureManager)& theMgr,
+                          const Handle(OpenGl_GraphicDriver)& theDriver,
+                          const Handle(OpenGl_Caps)& theCaps,
+                          Standard_Boolean& theDeviceLostFlag,
+                          OpenGl_StateCounter* theCounter)
+: Graphic3d_CView  (theMgr),
+  myDriver         (theDriver.operator->()),
+  myCaps           (theCaps),
+  myDeviceLostFlag (theDeviceLostFlag),
+  myWasRedrawnGL   (Standard_False),
+  myAntiAliasing   (Standard_False),
+  myCulling        (Standard_True),
+  myShadingModel   (Graphic3d_TOSM_FACET),
+  myBackfacing     (Graphic3d_TOBM_AUTOMATIC),
+  myBgColor        (myDefaultBg),
+  myFog            (myDefaultFog),
+  myZClip          (myDefaultZClip),
+  myCamera         (new Graphic3d_Camera()),
+  myUseGLLight     (Standard_True),
+  myToShowTrihedron      (false),
+  myToShowGradTrihedron  (false),
+  myStateCounter         (theCounter),
+  myLastLightSourceState (0, 0),
+  myFboColorFormat       (GL_RGBA8),
+  myFboDepthFormat       (GL_DEPTH24_STENCIL8),
+  myToFlipOutput         (Standard_False),
+  myFrameCounter         (0),
+  myHasFboBlit           (Standard_True),
+  myToDisableMSAA        (Standard_False),
+  myTransientDrawToFront (Standard_True),
+  myBackBufferRestored   (Standard_False),
+  myIsImmediateDrawn     (Standard_False),
+  myTextureParams   (new OpenGl_AspectFace()),
+  myBgGradientArray (new OpenGl_BackgroundArray (Graphic3d_TOB_GRADIENT)),
+  myBgTextureArray  (new OpenGl_BackgroundArray (Graphic3d_TOB_TEXTURE)),
+  // ray-tracing fields initialization
+  myRaytraceInitStatus     (OpenGl_RT_NONE),
+  myIsRaytraceDataValid    (Standard_False),
+  myIsRaytraceWarnTextures (Standard_False),
+  myToUpdateEnvironmentMap (Standard_False),
+  myLayerListState (0)
+{
+  myWorkspace = new OpenGl_Workspace (this, NULL);
 
-OpenGl_View::OpenGl_View (const CALL_DEF_VIEWCONTEXT &AContext)
-: mySurfaceDetail(Visual3d_TOD_NONE),
-  myBackfacing(0),
-  myBgTexture(myDefaultBgTexture),
-  myBgGradient(myDefaultBgGradient),
-  //myOrientationMatrix(myDefaultMatrix),
-  //myMappingMatrix(myDefaultMatrix),
-  //shield_indicator = TOn,
-  //shield_colour = { { 0.F, 0.F, 0.F, 1.F } },
-  //border_indicator = TOff,
-  //border_colour = { { 0.F, 0.F, 0.F, 1.F } },
-  //active_status = TOn,
-  myZClip(myDefaultZClip),
-  myExtra(myDefaultExtra),
-  myFog(myDefaultFog),
-  myVisualization(AContext.Visualization),
-  myIntShadingMethod(TEL_SM_GOURAUD),
-  myAntiAliasing(Standard_False),
-  myAnimationListIndex(0),
-  myAnimationListReady(Standard_False),
-  myTransPers(&myDefaultTransPers),
-  myIsTransPers(Standard_False),
-  myResetFLIST(Standard_False)
-{
-  // Initialize matrices
-  memcpy(myOrientationMatrix,myDefaultMatrix,sizeof(Tmatrix3));
-  memcpy(myMappingMatrix,myDefaultMatrix,sizeof(Tmatrix3));
-
-  // Shading method
-  switch (AContext.Model)
+  // AA mode
+  const char* anAaEnv = ::getenv ("CALL_OPENGL_ANTIALIASING_MODE");
+  if (anAaEnv != NULL)
   {
-    case 1 : /* VISUAL3D_TOM_INTERP_COLOR */
-    case 3 : /* VISUAL3D_TOM_VERTEX */
-      myIntShadingMethod = TEL_SM_GOURAUD;
-      break;
-    default :
-      myIntShadingMethod = TEL_SM_FLAT;
-      break;
+    int v;
+    if (sscanf (anAaEnv, "%d", &v) > 0) myAntiAliasing = v;
   }
-}
 
-/*----------------------------------------------------------------------*/
+  OpenGl_Light       aLight;
+  aLight.Type        = Graphic3d_TOLS_AMBIENT;
+  aLight.IsHeadlight = Standard_False;
+  aLight.Color.r()   = 1.;
+  aLight.Color.g()   = 1.;
+  aLight.Color.b()   = 1.;
+  myNoShadingLight.Append (aLight);
+
+  myCurrLightSourceState  = myStateCounter->Increment();
+  myMainSceneFbos[0]      = new OpenGl_FrameBuffer();
+  myMainSceneFbos[1]      = new OpenGl_FrameBuffer();
+  myImmediateSceneFbos[0] = new OpenGl_FrameBuffer();
+  myImmediateSceneFbos[1] = new OpenGl_FrameBuffer();
+  myOpenGlFBO             = new OpenGl_FrameBuffer();
+  myOpenGlFBO2            = new OpenGl_FrameBuffer();
+  myRaytraceFBO1[0]       = new OpenGl_FrameBuffer();
+  myRaytraceFBO1[1]       = new OpenGl_FrameBuffer();
+  myRaytraceFBO2[0]       = new OpenGl_FrameBuffer();
+  myRaytraceFBO2[1]       = new OpenGl_FrameBuffer();
+}
 
-OpenGl_View::~OpenGl_View ()
+// =======================================================================
+// function : Destructor
+// purpose  :
+// =======================================================================
+OpenGl_View::~OpenGl_View()
 {
   ReleaseGlResources (NULL); // ensure ReleaseGlResources() was called within valid context
+  OpenGl_Element::Destroy (NULL, myBgGradientArray);
+  OpenGl_Element::Destroy (NULL, myBgTextureArray);
+  OpenGl_Element::Destroy (NULL, myTextureParams);
 }
 
+// =======================================================================
+// function : ReleaseGlResources
+// purpose  :
+// =======================================================================
 void OpenGl_View::ReleaseGlResources (const Handle(OpenGl_Context)& theCtx)
 {
+  myTrihedron         .Release (theCtx.operator->());
+  myGraduatedTrihedron.Release (theCtx.operator->());
+
   if (!myTextureEnv.IsNull())
   {
     theCtx->DelayedRelease (myTextureEnv);
     myTextureEnv.Nullify();
   }
-  if (myBgTexture.TexId != 0)
-  {
-    glDeleteTextures (1, (GLuint*)&(myBgTexture.TexId));
-    myBgTexture.TexId = 0;
-  }
-  if (myAnimationListIndex)
+
+  if (myTextureParams != NULL)
   {
-    glDeleteLists ((GLuint )myAnimationListIndex, 1);
-    myAnimationListIndex = 0;
+    myTextureParams->Release (theCtx.operator->());
   }
-}
-
-void OpenGl_View::SetTextureEnv (const Handle(OpenGl_Context)&       theCtx,
-                                 const Handle(Graphic3d_TextureEnv)& theTexture)
-{
-  if (!myTextureEnv.IsNull())
+  if (myBgGradientArray != NULL)
   {
-    theCtx->DelayedRelease (myTextureEnv);
-    myTextureEnv.Nullify();
+    myBgGradientArray->Release (theCtx.operator->());
   }
-
-  if (theTexture.IsNull())
+  if (myBgTextureArray != NULL)
   {
-    return;
+    myBgTextureArray->Release (theCtx.operator->());
   }
 
-  myTextureEnv = new OpenGl_Texture (theTexture->GetParams());
-  Handle(Image_PixMap) anImage = theTexture->GetImage();
-  myTextureEnv->Init (theCtx, *anImage.operator->(), theTexture->Type());
-}
-
-/*----------------------------------------------------------------------*/
+  myMainSceneFbos[0]     ->Release (theCtx.operator->());
+  myMainSceneFbos[1]     ->Release (theCtx.operator->());
+  myImmediateSceneFbos[0]->Release (theCtx.operator->());
+  myImmediateSceneFbos[1]->Release (theCtx.operator->());
+  myOpenGlFBO            ->Release (theCtx.operator->());
+  myOpenGlFBO2           ->Release (theCtx.operator->());
+  myFullScreenQuad        .Release (theCtx.operator->());
+  myFullScreenQuadFlip    .Release (theCtx.operator->());
 
-void OpenGl_View::SetBackfacing (const Standard_Integer AMode)
-{
-  myBackfacing = AMode;
-  myResetFLIST = Standard_True;
+  releaseRaytraceResources (theCtx);
 }
 
-/*----------------------------------------------------------------------*/
-
-//call_togl_setlight
-void OpenGl_View::SetLights (const CALL_DEF_VIEWCONTEXT &AContext)
+// =======================================================================
+// function : Remove
+// purpose  :
+// =======================================================================
+void OpenGl_View::Remove()
 {
-  myLights.Clear();
-
-  const int nb_lights = AContext.NbActiveLight;
-
-  int i = 0;
-  const CALL_DEF_LIGHT *alight = &(AContext.ActiveLight[0]);
-  for ( ; i < nb_lights; i++, alight++ )
+  if (IsRemoved())
   {
-    OpenGl_Light rep;
-
-       switch( alight->LightType )
-    {
-      case 0 : /* TOLS_AMBIENT */
-        rep.type = TLightAmbient;
-        rep.col.rgb[0] = alight->Color.r;
-        rep.col.rgb[1] = alight->Color.g;
-        rep.col.rgb[2] = alight->Color.b;
-        break;
-
-      case 1 : /* TOLS_DIRECTIONAL */
-        rep.type = TLightDirectional;
-        rep.col.rgb[0] = alight->Color.r;
-        rep.col.rgb[1] = alight->Color.g;
-        rep.col.rgb[2] = alight->Color.b;
-        rep.dir[0] = alight->Direction.x;
-        rep.dir[1] = alight->Direction.y;
-        rep.dir[2] = alight->Direction.z;
-        break;
-
-      case 2 : /* TOLS_POSITIONAL */
-        rep.type = TLightPositional;
-        rep.col.rgb[0] = alight->Color.r;
-        rep.col.rgb[1] = alight->Color.g;
-        rep.col.rgb[2] = alight->Color.b;
-        rep.pos[0] = alight->Position.x;
-        rep.pos[1] = alight->Position.y;
-        rep.pos[2] = alight->Position.z;
-        rep.atten[0] = alight->Attenuation[0];
-        rep.atten[1] = alight->Attenuation[1];
-        break;
-
-      case 3 : /* TOLS_SPOT */
-        rep.type = TLightSpot;
-        rep.col.rgb[0] = alight->Color.r;
-        rep.col.rgb[1] = alight->Color.g;
-        rep.col.rgb[2] = alight->Color.b;
-        rep.pos[0] = alight->Position.x;
-        rep.pos[1] = alight->Position.y;
-        rep.pos[2] = alight->Position.z;
-        rep.dir[0] = alight->Direction.x;
-        rep.dir[1] = alight->Direction.y;
-        rep.dir[2] = alight->Direction.z;
-        rep.shine = alight->Concentration;
-        rep.atten[0] = alight->Attenuation[0];
-        rep.atten[1] = alight->Attenuation[1];
-        rep.angle = alight->Angle;
-        break;
-    }
+    return;
+  }
 
-    rep.HeadLight = alight->Headlight;
+  myDriver->RemoveView (this);
+  myWindow.Nullify();
 
-    myLights.Append(rep);
-  }
+  Graphic3d_CView::Remove();
 }
 
-/*----------------------------------------------------------------------*/
-
-//call_togl_setplane
-void OpenGl_View::SetClippingPlanes (const CALL_DEF_VIEWCONTEXT &AContext)
+// =======================================================================
+// function : SetTextureEnv
+// purpose  :
+// =======================================================================
+void OpenGl_View::SetTextureEnv (const Handle(Graphic3d_TextureEnv)& theTextureEnv)
 {
-  // clear clipping planes information
-  myClippingPlanes.Clear();
-  // update information
-  int i = 0;
-  for (; i < AContext.NbActivePlane; i++)
+  Handle(OpenGl_Context) aCtx = myWorkspace->GetGlContext();
+  if (!aCtx.IsNull() && !myTextureEnv.IsNull())
   {
-    const CALL_DEF_PLANE &aCPlane = AContext.ActivePlane[i];
-    if ( aCPlane.Active && aCPlane.PlaneId > 0 )
-    {
-      OPENGL_CLIP_REP aPlane;
-      aPlane.equation[0] = aCPlane.CoefA;
-      aPlane.equation[1] = aCPlane.CoefB;
-      aPlane.equation[2] = aCPlane.CoefC;
-      aPlane.equation[3] = aCPlane.CoefD;
-      myClippingPlanes.Append( aPlane );
-    }
+    aCtx->DelayedRelease (myTextureEnv);
   }
-}
 
-/*----------------------------------------------------------------------*/
+  myToUpdateEnvironmentMap = Standard_True;
+  myTextureEnvData = theTextureEnv;
+  myTextureEnv.Nullify();
+  initTextureEnv (aCtx);
+}
 
-//call_togl_setvisualisation
-void OpenGl_View::SetVisualisation (const CALL_DEF_VIEWCONTEXT &AContext)
+// =======================================================================
+// function : initTextureEnv
+// purpose  :
+// =======================================================================
+void OpenGl_View::initTextureEnv (const Handle(OpenGl_Context)& theContext)
 {
-  myVisualization = AContext.Visualization;
-  // Shading method
-  switch (AContext.Model)
+  if (myTextureEnvData.IsNull()
+    ||  theContext.IsNull()
+    || !theContext->MakeCurrent())
   {
-    case 1 : /* VISUAL3D_TOM_INTERP_COLOR */
-    case 3 : /* VISUAL3D_TOM_VERTEX */
-      myIntShadingMethod = TEL_SM_GOURAUD;
-      break;
-    default :
-      myIntShadingMethod = TEL_SM_FLAT;
-      break;
+    return;
   }
-}
-
-/*----------------------------------------------------------------------*/
 
-//call_togl_cliplimit
-void OpenGl_View::SetClipLimit (const Graphic3d_CView& theCView)
-{
-  myZClip.Back.Limit =
-    (theCView.Context.ZClipBackPlane     - theCView.Mapping.BackPlaneDistance) /
-    (theCView.Mapping.FrontPlaneDistance - theCView.Mapping.BackPlaneDistance);
-  myZClip.Front.Limit =
-    (theCView.Context.ZClipFrontPlane    - theCView.Mapping.BackPlaneDistance) /
-    (theCView.Mapping.FrontPlaneDistance - theCView.Mapping.BackPlaneDistance);
-  if (myZClip.Back.Limit < 0.0f)
-    myZClip.Back.Limit = 0.0f;
-  if (myZClip.Front.Limit > 1.0f)
-    myZClip.Front.Limit = 1.0f;
-  if (myZClip.Back.Limit > myZClip.Front.Limit)
+  myTextureEnv = new OpenGl_Texture (myTextureEnvData->GetParams());
+  Handle(Image_PixMap) anImage = myTextureEnvData->GetImage();
+  if (!anImage.IsNull())
   {
-    myZClip.Back.Limit  = 0.0f;
-    myZClip.Front.Limit = 1.0f;
+    myTextureEnv->Init (theContext, *anImage.operator->(), myTextureEnvData->Type());
   }
-
-  myZClip.Back.IsOn  = (theCView.Context.BackZClipping  != 0);
-  myZClip.Front.IsOn = (theCView.Context.FrontZClipping != 0);
 }
 
-/*----------------------------------------------------------------------*/
-
-//call_togl_viewmapping
-void OpenGl_View::SetMapping (const Graphic3d_CView& theCView)
+// =======================================================================
+// function : SetImmediateModeDrawToFront
+// purpose  :
+// =======================================================================
+Standard_Boolean OpenGl_View::SetImmediateModeDrawToFront (const Standard_Boolean theDrawToFrontBuffer)
 {
-  const float ratio   = theCView.DefWindow.dy / theCView.DefWindow.dx;
-  const float r_ratio = theCView.DefWindow.dx / theCView.DefWindow.dy;
-
-  TEL_VIEW_MAPPING Map;
+  const Standard_Boolean aPrevMode = myTransientDrawToFront;
+  myTransientDrawToFront = theDrawToFrontBuffer;
+  return aPrevMode;
+}
 
-  Map.window.xmin = theCView.Mapping.WindowLimit.um;
-  Map.window.ymin = theCView.Mapping.WindowLimit.vm;
-  Map.window.xmax = theCView.Mapping.WindowLimit.uM;
-  Map.window.ymax = theCView.Mapping.WindowLimit.vM;
+// =======================================================================
+// function : SetWindow
+// purpose  :
+// =======================================================================
+void OpenGl_View::SetWindow (const Handle(Aspect_Window)& theWindow,
+                             const Aspect_RenderingContext theContext)
+{
+  myWindow = myDriver->CreateRenderWindow (theWindow, theContext);
+  Standard_ASSERT_RAISE (!myWindow.IsNull(),
+                         "OpenGl_View::SetWindow, "
+                         "Failed to create OpenGl window.");
+
+  myWorkspace = new OpenGl_Workspace (this, myWindow);
+  myWorldViewProjState.Reset();
+  myToUpdateEnvironmentMap = Standard_True;
+  myHasFboBlit = Standard_True;
+  Invalidate();
+
+  // Environment texture resource does not support lazy initialization.
+  initTextureEnv (myWorkspace->GetGlContext());
+}
 
-  Map.viewport.xmin = 0.F;
-  Map.viewport.xmax = ( 1.F < r_ratio ? 1.F : r_ratio );
-  Map.viewport.ymin = 0.F;
-  Map.viewport.ymax = ( 1.F < ratio ? 1.F : ratio );
-  Map.viewport.zmin = 0.F;
-  Map.viewport.zmax = 1.F;
+// =======================================================================
+// function : Resized
+// purpose  :
+// =======================================================================
+void OpenGl_View::Resized()
+{
+  if (myWindow.IsNull())
+    return;
 
-  // projection type
-  switch (theCView.Mapping.Projection)
-  {
-    case 0 :
-      Map.proj = TelPerspective;
-      break;
-    case 1 :
-      Map.proj = TelParallel;
-      break;
-  }
+  myWindow->Resize();
+}
 
-  // projection reference point
-  Map.prp[0] = theCView.Mapping.ProjectionReferencePoint.x;
-  Map.prp[1] = theCView.Mapping.ProjectionReferencePoint.y;
-  Map.prp[2] = theCView.Mapping.ProjectionReferencePoint.z;
-  if (!openglDisplay.IsNull() && !openglDisplay->Walkthrough())
-    Map.prp[2] += theCView.Mapping.FrontPlaneDistance;
+// =======================================================================
+// function : TriedronDisplay
+// purpose  :
+// =======================================================================
+void OpenGl_View::TriedronDisplay (const Aspect_TypeOfTriedronPosition thePosition,
+                                   const Quantity_NameOfColor          theColor,
+                                   const Standard_Real                 theScale,
+                                   const Standard_Boolean              theAsWireframe)
+{
+  myToShowTrihedron = true;
+  myTrihedron.SetWireframe   (theAsWireframe);
+  myTrihedron.SetPosition    (thePosition);
+  myTrihedron.SetScale       (theScale);
+  myTrihedron.SetLabelsColor (theColor);
+}
 
-  // view plane distance
-  Map.vpd = theCView.Mapping.ViewPlaneDistance;
+// =======================================================================
+// function : TriedronErase
+// purpose  :
+// =======================================================================
+void OpenGl_View::TriedronErase()
+{
+  myToShowTrihedron = false;
+  myTrihedron.Release (myWorkspace->GetGlContext().operator->());
+}
 
-  // back plane distance
-  Map.bpd = theCView.Mapping.BackPlaneDistance;
+// =======================================================================
+// function : ZBufferTriedronSetup
+// purpose  :
+// =======================================================================
+void OpenGl_View::ZBufferTriedronSetup (const Quantity_NameOfColor theXColor,
+                                        const Quantity_NameOfColor theYColor,
+                                        const Quantity_NameOfColor theZColor,
+                                        const Standard_Real theSizeRatio,
+                                        const Standard_Real theAxisDiametr,
+                                        const Standard_Integer theNbFacettes)
+{
+  myTrihedron.SetArrowsColors  (theXColor, theYColor, theZColor);
+  myTrihedron.SetSizeRatio     (theSizeRatio);
+  myTrihedron.SetNbFacets      (theNbFacettes);
+  myTrihedron.SetArrowDiameter (theAxisDiametr);
+}
 
-  // front plane distance
-  Map.fpd = theCView.Mapping.FrontPlaneDistance;
+// =======================================================================
+// function : TriedronEcho
+// purpose  :
+// =======================================================================
+void OpenGl_View::TriedronEcho (const Aspect_TypeOfTriedronEcho /*theType*/)
+{
+  // do nothing
+}
 
-  Tint err_ind = 0;
+// =======================================================================
+// function : SetMinMaxValuesCallback
+// purpose  :
+// =======================================================================
+static void SetMinMaxValuesCallback (Graphic3d_CView* theView)
+{
+  OpenGl_View* aView = dynamic_cast<OpenGl_View*>(theView);
+  if (aView == NULL)
+    return;
 
-  // use user-defined matrix
-  if (theCView.Mapping.IsCustomMatrix)
+  Bnd_Box aBox = theView->MinMaxValues();
+  if (!aBox.IsVoid())
   {
-    int i, j;
-    for( i = 0; i < 4; i++ )
-      for( j = 0; j < 4; j++ )
-        myMappingMatrix[i][j] = theCView.Mapping.ProjectionMatrix[i][j];
+    gp_Pnt aMin = aBox.CornerMin();
+    gp_Pnt aMax = aBox.CornerMax();
+
+    Graphic3d_Vec3 aMinVec ((Standard_ShortReal )aMin.X(), (Standard_ShortReal )aMin.Y(), (Standard_ShortReal )aMin.Z());
+    Graphic3d_Vec3 aMaxVec ((Standard_ShortReal )aMax.X(), (Standard_ShortReal )aMax.Y(), (Standard_ShortReal )aMax.Z());
+    aView->GraduatedTrihedronMinMaxValues (aMinVec, aMaxVec);
   }
-  else
-    TelEvalViewMappingMatrix( &Map, &err_ind, myMappingMatrix );
+}
 
-  if (!err_ind)
-    myExtra.map = Map;
+// =======================================================================
+// function : GraduatedTrihedronDisplay
+// purpose  :
+// =======================================================================
+void OpenGl_View::GraduatedTrihedronDisplay (const Graphic3d_GraduatedTrihedron& theTrihedronData)
+{
+  myGTrihedronData = theTrihedronData;
+  myGTrihedronData.PtrView = this;
+  myGTrihedronData.CubicAxesCallback = SetMinMaxValuesCallback;
+  myGraduatedTrihedron.SetValues (myGTrihedronData);
+  myToShowGradTrihedron = true;
 }
 
-/*----------------------------------------------------------------------*/
+// =======================================================================
+// function : GraduatedTrihedronErase
+// purpose  :
+// =======================================================================
+void OpenGl_View::GraduatedTrihedronErase()
+{
+  myGTrihedronData.PtrView = NULL;
+  myGraduatedTrihedron.Release (myWorkspace->GetGlContext().operator->());
+  myToShowGradTrihedron = false;
+}
 
-//call_togl_vieworientation
-void OpenGl_View::SetOrientation (const Graphic3d_CView& theCView)
+// =======================================================================
+// function : GraduatedTrihedronMinMaxValues
+// purpose  :
+// =======================================================================
+void OpenGl_View::GraduatedTrihedronMinMaxValues (const Graphic3d_Vec3 theMin, const Graphic3d_Vec3 theMax)
 {
-  Tfloat Vrp[3];
-  Tfloat Vpn[3];
-  Tfloat Vup[3];
-  Tfloat ScaleFactors[3];
+  myGraduatedTrihedron.SetMinMax (theMin, theMax);
+}
 
-  Vrp[0] = theCView.Orientation.ViewReferencePoint.x;
-  Vrp[1] = theCView.Orientation.ViewReferencePoint.y;
-  Vrp[2] = theCView.Orientation.ViewReferencePoint.z;
+// =======================================================================
+// function : BufferDump
+// purpose  :
+// =======================================================================
+Standard_Boolean OpenGl_View::BufferDump (Image_PixMap& theImage, const Graphic3d_BufferType& theBufferType)
+{
+  return myWorkspace->BufferDump (myFBO, theImage, theBufferType);
+}
 
-  Vpn[0] = theCView.Orientation.ViewReferencePlane.x;
-  Vpn[1] = theCView.Orientation.ViewReferencePlane.y;
-  Vpn[2] = theCView.Orientation.ViewReferencePlane.z;
+// =======================================================================
+// function : Background
+// purpose  :
+// =======================================================================
+Aspect_Background OpenGl_View::Background() const
+{
+  return Aspect_Background (Quantity_Color (myBgColor.rgb[0], myBgColor.rgb[1], myBgColor.rgb[2], Quantity_TOC_RGB));
+}
 
-  Vup[0] = theCView.Orientation.ViewReferenceUp.x;
-  Vup[1] = theCView.Orientation.ViewReferenceUp.y;
-  Vup[2] = theCView.Orientation.ViewReferenceUp.z;
+// =======================================================================
+// function : SetBackground
+// purpose  :
+// =======================================================================
+void OpenGl_View::SetBackground (const Aspect_Background& theBackground)
+{
+  Quantity_Color aBgColor = theBackground.Color();
+  myBgColor.rgb[0] = static_cast<float> (aBgColor.Red());
+  myBgColor.rgb[1] = static_cast<float> (aBgColor.Green());
+  myBgColor.rgb[2] = static_cast<float> (aBgColor.Blue());
+  myFog.Color      = myBgColor;
+}
 
-  ScaleFactors[0] = theCView.Orientation.ViewScaleX;
-  ScaleFactors[1] = theCView.Orientation.ViewScaleY;
-  ScaleFactors[2] = theCView.Orientation.ViewScaleZ;
+// =======================================================================
+// function : GradientBackground
+// purpose  :
+// =======================================================================
+Aspect_GradientBackground OpenGl_View::GradientBackground() const
+{
+  Quantity_Color aColor1, aColor2;
+  aColor1.SetValues (myBgGradientArray->GradientColor (0).r(),
+                     myBgGradientArray->GradientColor (0).g(),
+                     myBgGradientArray->GradientColor (0).b(), Quantity_TOC_RGB);
+  aColor2.SetValues (myBgGradientArray->GradientColor (1).r(),
+                     myBgGradientArray->GradientColor (1).g(),
+                     myBgGradientArray->GradientColor (1).b(), Quantity_TOC_RGB);
+  return Aspect_GradientBackground (aColor1, aColor2, myBgGradientArray->GradientFillMethod());
+}
 
-  Tint err_ind = 0;
+// =======================================================================
+// function : SetGradientBackground
+// purpose  :
+// =======================================================================
+void OpenGl_View::SetGradientBackground (const Aspect_GradientBackground& theBackground)
+{
+  Quantity_Color aColor1, aColor2;
+  theBackground.Colors (aColor1, aColor2);
+  myBgGradientArray->SetGradientParameters (aColor1, aColor2, theBackground.BgGradientFillMethod());
+}
 
-  // use user-defined matrix
-  if (theCView.Orientation.IsCustomMatrix)
+// =======================================================================
+// function : SetBackgroundImage
+// purpose  :
+// =======================================================================
+void OpenGl_View::SetBackgroundImage (const TCollection_AsciiString& theFilePath)
+{
+  // Prepare aspect for texture storage
+  myBackgroundImagePath = theFilePath;
+  Handle(Graphic3d_AspectFillArea3d) anAspect = new Graphic3d_AspectFillArea3d();
+  Handle(Graphic3d_Texture2Dmanual) aTextureMap = new Graphic3d_Texture2Dmanual (TCollection_AsciiString (theFilePath));
+  aTextureMap->EnableRepeat();
+  aTextureMap->DisableModulate();
+  aTextureMap->GetParams()->SetGenMode (Graphic3d_TOTM_MANUAL,
+                                        Graphic3d_Vec4 (0.0f, 0.0f, 0.0f, 0.0f),
+                                        Graphic3d_Vec4 (0.0f, 0.0f, 0.0f, 0.0f));
+  anAspect->SetTextureMap (aTextureMap);
+  anAspect->SetInteriorStyle (Aspect_IS_SOLID);
+  // Enable texture mapping
+  if (aTextureMap->IsDone())
   {
-    int i, j;
-    for( i = 0; i < 4; i++ )
-      for( j = 0; j < 4; j++ )
-        myOrientationMatrix[i][j] = theCView.Orientation.ModelViewMatrix[i][j];
+    anAspect->SetTextureMapOn();
   }
   else
   {
-    TelEvalViewOrientationMatrix (Vrp, Vpn, Vup, ScaleFactors, &err_ind, myOrientationMatrix);
+    anAspect->SetTextureMapOff();
+    return;
   }
 
-  if (!err_ind)
-  {
-    myExtra.vrp[0] = Vrp[0];
-    myExtra.vrp[1] = Vrp[1];
-    myExtra.vrp[2] = Vrp[2];
+  // Set texture parameters
+  myTextureParams->SetAspect (anAspect);
+}
 
-    myExtra.vpn[0] = Vpn[0];
-    myExtra.vpn[1] = Vpn[1];
-    myExtra.vpn[2] = Vpn[2];
+// =======================================================================
+// function : BackgroundImageStyle
+// purpose  :
+// =======================================================================
+Aspect_FillMethod OpenGl_View::BackgroundImageStyle() const
+{
+  return myBgTextureArray->TextureFillMethod();
+}
 
-    myExtra.vup[0] = Vup[0];
-    myExtra.vup[1] = Vup[1];
-    myExtra.vup[2] = Vup[2];
+// =======================================================================
+// function : SetBackgroundImageStyle
+// purpose  :
+// =======================================================================
+void OpenGl_View::SetBackgroundImageStyle (const Aspect_FillMethod theFillStyle)
+{
+  myBgTextureArray->SetTextureFillMethod (theFillStyle);
+}
 
-    myExtra.scaleFactors[0] = ScaleFactors[0],
-    myExtra.scaleFactors[1] = ScaleFactors[1],
-    myExtra.scaleFactors[2] = ScaleFactors[2];
-  }
+//=======================================================================
+//function : AddZLayer
+//purpose  :
+//=======================================================================
+void OpenGl_View::AddZLayer (const Graphic3d_ZLayerId theLayerId)
+{
+  myZLayers.AddLayer (theLayerId);
 }
 
-/*----------------------------------------------------------------------*/
+//=======================================================================
+//function : RemoveZLayer
+//purpose  :
+//=======================================================================
+void OpenGl_View::RemoveZLayer (const Graphic3d_ZLayerId theLayerId)
+{
+  myZLayers.RemoveLayer (theLayerId);
+}
 
-void OpenGl_View::SetFog (const Graphic3d_CView& theCView,
-                          const Standard_Boolean theFlag)
+//=======================================================================
+//function : SetZLayerSettings
+//purpose  :
+//=======================================================================
+void OpenGl_View::SetZLayerSettings (const Graphic3d_ZLayerId        theLayerId,
+                                     const Graphic3d_ZLayerSettings& theSettings)
 {
-  if (!theFlag)
+  myZLayers.SetLayerSettings (theLayerId, theSettings);
+}
+
+//=======================================================================
+//function : ZLayerMax
+//purpose  :
+//=======================================================================
+Standard_Integer OpenGl_View::ZLayerMax() const
+{
+  Standard_Integer aLayerMax = Graphic3d_ZLayerId_Default;
+  for (OpenGl_LayerSeqIds::Iterator aMapIt(myZLayers.LayerIDs()); aMapIt.More(); aMapIt.Next())
   {
-    myFog.IsOn = Standard_False;
+    aLayerMax = Max (aLayerMax, aMapIt.Value());
   }
-  else
-  {
-    myFog.IsOn = Standard_True;
-
-    myFog.Front =
-      (theCView.Context.DepthFrontPlane    - theCView.Mapping.BackPlaneDistance) /
-      (theCView.Mapping.FrontPlaneDistance - theCView.Mapping.BackPlaneDistance);
-
-    myFog.Back =
-      (theCView.Context.DepthBackPlane     - theCView.Mapping.BackPlaneDistance) /
-      (theCView.Mapping.FrontPlaneDistance - theCView.Mapping.BackPlaneDistance);
-
-    if (myFog.Front < 0.F)
-      myFog.Front = 0.F;
-    else if (myFog.Front > 1.F)
-      myFog.Front = 1.F;
 
-    if (myFog.Back < 0.F)
-      myFog.Back = 0.F;
-    else if (myFog.Back > 1.F)
-      myFog.Back = 1.F;
+  return aLayerMax;
+}
 
-    if (myFog.Back > myFog.Front)
+//=======================================================================
+//function : InvalidateZLayerBoundingBox
+//purpose  :
+//=======================================================================
+void OpenGl_View::InvalidateZLayerBoundingBox (const Graphic3d_ZLayerId theLayerId) const
+{
+  if (myZLayers.LayerIDs().IsBound (theLayerId))
+  {
+    myZLayers.Layer (theLayerId).InvalidateBoundingBox();
+  }
+  else
+  {
+    for (Standard_Integer aLayerId = Graphic3d_ZLayerId_Default; aLayerId < ZLayerMax(); ++aLayerId)
     {
-      myFog.Front = 1.F;
-      myFog.Back = 0.F;
+      if (myZLayers.LayerIDs().IsBound (aLayerId))
+      {
+        const OpenGl_Layer& aLayer = myZLayers.Layer (aLayerId);
+        if (aLayer.NbOfTransformPersistenceObjects() > 0)
+        {
+          aLayer.InvalidateBoundingBox();
+        }
+      }
     }
-
-    myFog.Color.rgb[0] = theCView.DefWindow.Background.r;
-    myFog.Color.rgb[1] = theCView.DefWindow.Background.g;
-    myFog.Color.rgb[2] = theCView.DefWindow.Background.b;
-    myFog.Color.rgb[3] = 1.0f;
   }
 }
 
-/*----------------------------------------------------------------------*/
-
-void OpenGl_View::TriedronDisplay (const Aspect_TypeOfTriedronPosition APosition, const Quantity_NameOfColor AColor,
-                                  const Standard_Real AScale, const Standard_Boolean AsWireframe)
+//=======================================================================
+//function : ZLayerBoundingBox
+//purpose  :
+//=======================================================================
+Graphic3d_BndBox4f OpenGl_View::ZLayerBoundingBox (const Graphic3d_ZLayerId        theLayerId,
+                                                   const Handle(Graphic3d_Camera)& theCamera,
+                                                   const Standard_Integer          theWindowWidth,
+                                                   const Standard_Integer          theWindowHeight,
+                                                   const Standard_Boolean          theToIgnoreInfiniteFlag) const
 {
-  myTrihedron = new OpenGl_Trihedron (APosition, AColor, AScale, AsWireframe);
-}
+  if (myZLayers.LayerIDs().IsBound (theLayerId))
+  {
+    return myZLayers.Layer (theLayerId).BoundingBox (Identification(),
+                                                     theCamera,
+                                                     theWindowWidth,
+                                                     theWindowHeight,
+                                                     theToIgnoreInfiniteFlag);
+  }
 
-/*----------------------------------------------------------------------*/
+  return Graphic3d_BndBox4f();
+}
 
-void OpenGl_View::TriedronErase ()
+//=======================================================================
+//function : considerZoomPersistenceObjects
+//purpose  :
+//=======================================================================
+Standard_Real OpenGl_View::considerZoomPersistenceObjects (const Graphic3d_ZLayerId        theLayerId,
+                                                           const Handle(Graphic3d_Camera)& theCamera,
+                                                           const Standard_Integer          theWindowWidth,
+                                                           const Standard_Integer          theWindowHeight,
+                                                           const Standard_Boolean          theToIgnoreInfiniteFlag) const
 {
-  myTrihedron.Nullify();
-}
+  if (myZLayers.LayerIDs().IsBound (theLayerId) && theCamera->IsOrthographic())
+  {
+    return myZLayers.Layer (theLayerId).considerZoomPersistenceObjects (Identification(),
+                                                                        theCamera,
+                                                                        theWindowWidth,
+                                                                        theWindowHeight,
+                                                                        theToIgnoreInfiniteFlag);
+  }
 
-/*----------------------------------------------------------------------*/
+  return 1.0;
+}
 
-void OpenGl_View::GraduatedTrihedronDisplay (const Graphic3d_CGraduatedTrihedron &data)
+//=======================================================================
+//function : FBO
+//purpose  :
+//=======================================================================
+Handle(Standard_Transient) OpenGl_View::FBO() const
 {
-  myGraduatedTrihedron = new OpenGl_GraduatedTrihedron(data);
+  return Handle(Standard_Transient)(myFBO);
 }
 
-/*----------------------------------------------------------------------*/
-
-void OpenGl_View::GraduatedTrihedronErase ()
+//=======================================================================
+//function : SetFBO
+//purpose  :
+//=======================================================================
+void OpenGl_View::SetFBO (const Handle(Standard_Transient)& theFbo)
 {
-  myGraduatedTrihedron.Nullify();
+  myFBO = Handle(OpenGl_FrameBuffer)::DownCast (theFbo);
 }
 
-/*----------------------------------------------------------------------*/
+//=======================================================================
+//function : FBOCreate
+//purpose  :
+//=======================================================================
+Handle(Standard_Transient) OpenGl_View::FBOCreate (const Standard_Integer theWidth,
+                                                   const Standard_Integer theHeight)
+{
+  return myWorkspace->FBOCreate (theWidth, theHeight);
+}
 
-//transform_persistence_end
-void OpenGl_View::EndTransformPersistence ()
+//=======================================================================
+//function : FBORelease
+//purpose  :
+//=======================================================================
+void OpenGl_View::FBORelease (Handle(Standard_Transient)& theFbo)
 {
-  if ( myIsTransPers )
+  Handle(OpenGl_FrameBuffer) aFrameBuffer = Handle(OpenGl_FrameBuffer)::DownCast (theFbo);
+  if (aFrameBuffer.IsNull())
   {
-    /* restore matrix */
-    glMatrixMode (GL_PROJECTION);
-    glPopMatrix ();
-    glMatrixMode (GL_MODELVIEW);
-    glPopMatrix ();
-    myIsTransPers = Standard_False;
+    return;
   }
-}
 
-/*----------------------------------------------------------------------*/
+  myWorkspace->FBORelease (aFrameBuffer);
+  theFbo.Nullify();
+}
 
-//transform_persistence_begin
-const TEL_TRANSFORM_PERSISTENCE * OpenGl_View::BeginTransformPersistence (const TEL_TRANSFORM_PERSISTENCE *ATransPers)
+//=======================================================================
+//function : FBOGetDimensions
+//purpose  :
+//=======================================================================
+void OpenGl_View::FBOGetDimensions (const Handle(Standard_Transient)& theFbo,
+                                    Standard_Integer& theWidth,
+                                    Standard_Integer& theHeight,
+                                    Standard_Integer& theWidthMax,
+                                    Standard_Integer& theHeightMax)
 {
-  const TEL_TRANSFORM_PERSISTENCE *TransPers_old = myTransPers;
-
-  myTransPers = ATransPers;
-
-  if ( ATransPers->mode == 0 )
+  const Handle(OpenGl_FrameBuffer) aFrameBuffer = Handle(OpenGl_FrameBuffer)::DownCast (theFbo);
+  if (aFrameBuffer.IsNull())
   {
-    EndTransformPersistence();
-    return TransPers_old;
+    return;
   }
 
-  GLint viewport[4];
-  glGetIntegerv (GL_VIEWPORT, viewport);
-  GLdouble modelMatrix[4][4];
-  glGetDoublev( GL_MODELVIEW_MATRIX,  (GLdouble *) modelMatrix );
-  GLdouble projMatrix[4][4];
-  glGetDoublev( GL_PROJECTION_MATRIX, (GLdouble *) projMatrix );
-
-  double W = viewport[2];
-  double H = viewport[3];
+  theWidth     = aFrameBuffer->GetVPSizeX(); // current viewport size
+  theHeight    = aFrameBuffer->GetVPSizeY();
+  theWidthMax  = aFrameBuffer->GetSizeX(); // texture size
+  theHeightMax = aFrameBuffer->GetSizeY();
+}
 
-  if ( myIsTransPers )
+//=======================================================================
+//function : FBOChangeViewport
+//purpose  :
+//=======================================================================
+void OpenGl_View::FBOChangeViewport (const Handle(Standard_Transient)& theFbo,
+                                     const Standard_Integer theWidth,
+                                     const Standard_Integer theHeight)
+{
+  const Handle(OpenGl_FrameBuffer) aFrameBuffer = Handle(OpenGl_FrameBuffer)::DownCast (theFbo);
+  if (aFrameBuffer.IsNull())
   {
-    /* restore matrix */
-    glMatrixMode (GL_PROJECTION);
-    glPopMatrix ();
-    glMatrixMode (GL_MODELVIEW);
-    glPopMatrix ();
+    return;
   }
-  else
-    myIsTransPers = Standard_True;
 
-  glMatrixMode( GL_MODELVIEW );
-  glPushMatrix();
-  glLoadIdentity();
-
-  glMatrixMode( GL_PROJECTION );
-  glPushMatrix();
-  glLoadIdentity();
+  aFrameBuffer->ChangeViewport (theWidth, theHeight);
+}
 
-  /*pre loading matrix*/
-  if( ATransPers->mode & TPF_PAN )
-    /* Annulate translate matrix */
+// =======================================================================
+// function : Export
+// purpose  :
+// =======================================================================
+#ifdef HAVE_GL2PS
+Standard_Boolean OpenGl_View::Export (const Standard_CString theFileName,
+                                      const Graphic3d_ExportFormat theFormat,
+                                      const Graphic3d_SortType theSortType)
+{
+  // gl2psBeginPage() will call OpenGL functions
+  // so we should activate correct GL context before redraw scene call
+  if (!myWorkspace->Activate())
   {
-    modelMatrix[3][0] = 0.;
-    modelMatrix[3][1] = 0.;
-    modelMatrix[3][2] = 0.;
-    projMatrix[3][0] = 0.;
-    projMatrix[3][1] = 0.;
-    projMatrix[3][2] = 0.;
+    return Standard_False;
   }
 
-  if( ATransPers->mode & TPF_ZOOM )
-    /* Annulate zoom matrix */
+  Standard_Integer aFormat = -1;
+  Standard_Integer aSortType = Graphic3d_ST_BSP_Tree;
+  switch (theFormat)
   {
-    const double scaleX = myExtra.scaleFactors[0];
-    const double scaleY = myExtra.scaleFactors[1];
-    const double scaleZ = myExtra.scaleFactors[2];
-
-    for (int i = 0; i < 3; ++i)
-    {
-      modelMatrix[0][i] /= scaleX;
-      modelMatrix[1][i] /= scaleY;
-      modelMatrix[2][i] /= scaleZ;
-    }
-
-    const double det2 = 0.002 / ( W > H ? projMatrix[1][1] : projMatrix[0][0]);
-    projMatrix[0][0] *= det2;
-    projMatrix[1][1] *= det2;
+    case Graphic3d_EF_PostScript:
+      aFormat = GL2PS_PS;
+      break;
+    case Graphic3d_EF_EnhPostScript:
+      aFormat = GL2PS_EPS;
+      break;
+    case Graphic3d_EF_TEX:
+      aFormat = GL2PS_TEX;
+      break;
+    case Graphic3d_EF_PDF:
+      aFormat = GL2PS_PDF;
+      break;
+    case Graphic3d_EF_SVG:
+      aFormat = GL2PS_SVG;
+      break;
+    case Graphic3d_EF_PGF:
+      aFormat = GL2PS_PGF;
+      break;
+    case Graphic3d_EF_EMF:
+      //aFormat = GL2PS_EMF;
+      aFormat = GL2PS_PGF + 1; // 6
+      break;
+    default:
+      // unsupported format
+      return Standard_False;
   }
 
-  if( ATransPers->mode & TPF_ROTATE )
-    /* Annulate rotate matrix */
-  {
-    modelMatrix[0][0] = 1.;
-    modelMatrix[1][1] = 1.;
-    modelMatrix[2][2] = 1.;
-
-    modelMatrix[1][0] = 0.;
-    modelMatrix[2][0] = 0.;
-    modelMatrix[0][1] = 0.;
-    modelMatrix[2][1] = 0.;
-    modelMatrix[0][2] = 0.;
-    modelMatrix[1][2] = 0.;
-  }
-  else if( ATransPers->mode & TPF_RELATIVE_ROTATE )
-    /* Initialize relative rotate matrix*/
+  switch (theSortType)
   {
-    modelMatrix[3][0] = 0.;
-    modelMatrix[3][1] = 0.;
-    modelMatrix[3][2] = 0.;
-
-    glMatrixMode( GL_MODELVIEW );
-    glLoadIdentity();
-    glTranslated( ATransPers->pointX, ATransPers->pointY, ATransPers->pointZ );
+    case Graphic3d_ST_Simple:
+      aSortType = GL2PS_SIMPLE_SORT;
+      break;
+    case Graphic3d_ST_BSP_Tree:
+      aSortType = GL2PS_BSP_SORT;
+      break;
   }
 
-  if( ATransPers->mode == TPF_TRIEDRON )
-  {
-    /* Annulate translation matrix */
-    modelMatrix[3][0] = 0.;
-    modelMatrix[3][1] = 0.;
-    modelMatrix[3][2] = 0.;
-
-    projMatrix[3][0] = 0.;
-    projMatrix[3][1] = 0.;
-    projMatrix[3][2] = 0.;
-
-    const double det2 = 0.002 / ( W > H ? projMatrix[1][1] : projMatrix[0][0]);
-    projMatrix[0][0] *= det2;
-    projMatrix[1][1] *= det2;
-  }
+  GLint aViewport[4];
+  aViewport[0] = 0;
+  aViewport[1] = 0;
+  aViewport[2] = myWindow->Width();
+  aViewport[3] = myWindow->Height();
 
-  /* load matrix */
-  glMatrixMode (GL_MODELVIEW);
-  glMultMatrixd ((GLdouble *) modelMatrix);
+  GLint aBufferSize = 1024 * 1024;
+  GLint anErrCode = GL2PS_SUCCESS;
 
-  glMatrixMode (GL_PROJECTION);
-  glMultMatrixd ((GLdouble *) projMatrix);
+  // gl2ps uses standard write functions and do not check locale
+  Standard_CLocaleSentry aLocaleSentry;
 
-  /*post loading matrix*/
-  if( ATransPers->mode == TPF_TRIEDRON )
+  while (aBufferSize > 0)
   {
-    glMatrixMode( GL_PROJECTION );
-
-       double winx, winy, winz;
-    const GLdouble idenMatrix[4][4] = { {1.,0.,0.,0.}, {0.,1.,0.,0.}, {0.,0.,1.,0.}, {0.,0.,0.,1.} };
-
-    gluUnProject( W/2., H/2., 0., (GLdouble*)idenMatrix, (GLdouble*)projMatrix, (GLint*)viewport, &winx, &winy, &winz);
-    double W1, H1;
-    W1 = winx;
-    H1 = winy;
-    gluUnProject( -W/2., -H/2., 0., (GLdouble*)idenMatrix, (GLdouble*)projMatrix, (GLint*)viewport, &winx, &winy, &winz);
-    double W2, H2;
-    W2 = winx;
-    H2 = winy;
-
-    if( ATransPers->pointX == 0. && ATransPers->pointY == 0. )
-    {
-      /*center*/
-    }
-    else if( ATransPers->pointX > 0. && ATransPers->pointY > 0. )
+    // current patch for EMF support in gl2ps uses WinAPI functions to create file
+    FILE* aFileH = (theFormat != Graphic3d_EF_EMF) ? fopen (theFileName, "wb") : NULL;
+    anErrCode = gl2psBeginPage ("", "", aViewport, aFormat, aSortType,
+                    GL2PS_DRAW_BACKGROUND | GL2PS_OCCLUSION_CULL | GL2PS_BEST_ROOT/* | GL2PS_SIMPLE_LINE_OFFSET*/,
+                    GL_RGBA, 0, NULL,
+                    0, 0, 0, aBufferSize, aFileH, theFileName);
+    if (anErrCode != GL2PS_SUCCESS)
     {
-      /*right upper*/
-      glTranslated( 0.5*(W1 - W2 - ATransPers->pointZ), 0.5*(H1 - H2 - ATransPers->pointZ), 0. );
-    }
-    else if( ATransPers->pointX > 0. && ATransPers->pointY < 0. )
-    {
-      /*right lower*/
-      glTranslated( 0.5*(W1 - W2 - ATransPers->pointZ), 0.5*(H2 - H1 + ATransPers->pointZ), 0. );
-    }
-    else if( ATransPers->pointX < 0. && ATransPers->pointY > 0. )
-    {
-      /*left upper*/
-      glTranslated( 0.5*(W2 - W1 + ATransPers->pointZ), 0.5*(H1 - H2 - ATransPers->pointZ), 0. );
-    }
-    else if( ATransPers->pointX < 0 && ATransPers->pointY < 0 )
-    {
-      /*left lower*/
-      glTranslated( -(W1 - W2)/2. + ATransPers->pointZ/2., -(H1-H2)/2. + ATransPers->pointZ/2., 0. );
+      // initialization failed
+      if (aFileH != NULL)
+        fclose (aFileH);
+      break;
     }
+    Redraw();
+
+    anErrCode = gl2psEndPage();
+    if (aFileH != NULL)
+      fclose (aFileH);
+
+    if (anErrCode == GL2PS_OVERFLOW)
+      aBufferSize *= 2;
+    else
+      break;
   }
+  return anErrCode == GL2PS_SUCCESS;
+}
+#else
+Standard_Boolean OpenGl_View::Export (const Standard_CString /*theFileName*/,
+                                      const Graphic3d_ExportFormat /*theFormat*/,
+                                      const Graphic3d_SortType /*theSortType*/)
+{
+    return Standard_False;
+}
+#endif
+
+//=======================================================================
+//function : displayStructure
+//purpose  :
+//=======================================================================
+void OpenGl_View::displayStructure (const Handle(Graphic3d_CStructure)& theStructure,
+                                    const Standard_Integer              thePriority)
+{
+  const OpenGl_Structure*  aStruct = reinterpret_cast<const OpenGl_Structure*> (theStructure.operator->());
+  const Graphic3d_ZLayerId aZLayer = aStruct->ZLayer();
+  myZLayers.AddStructure (aStruct, aZLayer, thePriority);
+}
 
-  return TransPers_old;
+//=======================================================================
+//function : eraseStructure
+//purpose  :
+//=======================================================================
+void OpenGl_View::eraseStructure (const Handle(Graphic3d_CStructure)& theStructure)
+{
+  const OpenGl_Structure*  aStruct = reinterpret_cast<const OpenGl_Structure*> (theStructure.operator->());
+  myZLayers.RemoveStructure (aStruct);
 }
 
-/*----------------------------------------------------------------------*/
+//=======================================================================
+//function : changeZLayer
+//purpose  :
+//=======================================================================
+void OpenGl_View::changeZLayer (const Handle(Graphic3d_CStructure)& theStructure,
+                                const Graphic3d_ZLayerId theNewLayerId)
+{
+  const Graphic3d_ZLayerId anOldLayer = theStructure->ZLayer();
+  const OpenGl_Structure* aStruct = reinterpret_cast<const OpenGl_Structure*> (theStructure.operator->());
+  myZLayers.ChangeLayer (aStruct, anOldLayer, theNewLayerId);
+  Update (Aspect_TOU_WAIT, anOldLayer);
+  Update (Aspect_TOU_WAIT, theNewLayerId);
+}
+
+//=======================================================================
+//function : changePriority
+//purpose  :
+//=======================================================================
+void OpenGl_View::changePriority (const Handle(Graphic3d_CStructure)& theStructure,
+                                  const Standard_Integer theNewPriority)
+{
+  const Graphic3d_ZLayerId aLayerId = theStructure->ZLayer();
+  const OpenGl_Structure* aStruct = reinterpret_cast<const OpenGl_Structure*> (theStructure.operator->());
+  myZLayers.ChangePriority (aStruct, aLayerId, theNewPriority);
+}