f71f85410fb46cf2ce79fee8a74e72deee88e117
[occt.git] / src / OpenGl / OpenGl_View_Redraw.cxx
1 // Created on: 2011-09-20
2 // Created by: Sergey ZERCHANINOV
3 // Copyright (c) 2011-2014 OPEN CASCADE SAS
4 //
5 // This file is part of Open CASCADE Technology software library.
6 //
7 // This library is free software; you can redistribute it and/or modify it under
8 // the terms of the GNU Lesser General Public License version 2.1 as published
9 // by the Free Software Foundation, with special exception defined in the file
10 // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
11 // distribution for complete text of the license and disclaimer of any warranty.
12 //
13 // Alternatively, this file may be used under the terms of Open CASCADE
14 // commercial license or contractual agreement.
15
16 #include <stdio.h>
17 #include <stdlib.h>
18
19 #include <OpenGl_GlCore11.hxx>
20
21 #include <Aspect_XRSession.hxx>
22 #include <Graphic3d_GraphicDriver.hxx>
23 #include <Graphic3d_StructureManager.hxx>
24 #include <Graphic3d_TextureParams.hxx>
25 #include <Graphic3d_Texture2Dmanual.hxx>
26 #include <Graphic3d_TransformUtils.hxx>
27 #include <Image_AlienPixMap.hxx>
28
29 #include <NCollection_Mat4.hxx>
30
31 #include <OpenGl_Context.hxx>
32 #include <OpenGl_FrameStats.hxx>
33 #include <OpenGl_Matrix.hxx>
34 #include <OpenGl_Workspace.hxx>
35 #include <OpenGl_View.hxx>
36 #include <OpenGl_GraduatedTrihedron.hxx>
37 #include <OpenGl_PrimitiveArray.hxx>
38 #include <OpenGl_ShaderManager.hxx>
39 #include <OpenGl_ShaderProgram.hxx>
40 #include <OpenGl_Structure.hxx>
41 #include <OpenGl_ArbFBO.hxx>
42
43 #include "../Textures/Textures_EnvLUT.pxx"
44
45 namespace
46 {
47   //! Format Frame Buffer format for logging messages.
48   static TCollection_AsciiString printFboFormat (const Handle(OpenGl_FrameBuffer)& theFbo)
49   {
50     return TCollection_AsciiString() + theFbo->GetInitVPSizeX() + "x" + theFbo->GetInitVPSizeY() + "@" + theFbo->NbSamples();
51   }
52
53   //! Return TRUE if Frame Buffer initialized has failed with the same parameters.
54   static bool checkWasFailedFbo (const Handle(OpenGl_FrameBuffer)& theFboToCheck,
55                                  Standard_Integer theSizeX,
56                                  Standard_Integer theSizeY,
57                                  Standard_Integer theNbSamples)
58   {
59     return !theFboToCheck->IsValid()
60         &&  theFboToCheck->GetInitVPSizeX() == theSizeX
61         &&  theFboToCheck->GetInitVPSizeY() == theSizeY
62         &&  theFboToCheck->NbSamples()      == theNbSamples;
63   }
64
65   //! Return TRUE if Frame Buffer initialized has failed with the same parameters.
66   static bool checkWasFailedFbo (const Handle(OpenGl_FrameBuffer)& theFboToCheck,
67                                  const Handle(OpenGl_FrameBuffer)& theFboRef)
68   {
69     return checkWasFailedFbo (theFboToCheck, theFboRef->GetVPSizeX(), theFboRef->GetVPSizeY(), theFboRef->NbSamples());
70   }
71 }
72
73 //=======================================================================
74 //function : drawBackground
75 //purpose  :
76 //=======================================================================
77 void OpenGl_View::drawBackground (const Handle(OpenGl_Workspace)& theWorkspace,
78                                   Graphic3d_Camera::Projection theProjection)
79 {
80   const Handle(OpenGl_Context)& aCtx = theWorkspace->GetGlContext();
81   const Standard_Boolean wasUsedZBuffer = theWorkspace->SetUseZBuffer (Standard_False);
82   if (wasUsedZBuffer)
83   {
84     aCtx->core11fwd->glDisable (GL_DEPTH_TEST);
85   }
86
87   if (myBackgroundType == Graphic3d_TOB_CUBEMAP)
88   {
89     myCubeMapParams->Aspect()->ShaderProgram()->PushVariableInt ("uZCoeff", myBackgroundCubeMap->ZIsInverted() ? -1 : 1);
90     myCubeMapParams->Aspect()->ShaderProgram()->PushVariableInt ("uYCoeff", myBackgroundCubeMap->IsTopDown() ? 1 : -1);
91     const OpenGl_Aspects* anOldAspectFace = theWorkspace->SetAspects (myCubeMapParams);
92
93     myBackgrounds[Graphic3d_TOB_CUBEMAP]->Render (theWorkspace, theProjection);
94
95     theWorkspace->SetAspects (anOldAspectFace);
96   }
97   else if (myBackgroundType == Graphic3d_TOB_GRADIENT
98         || myBackgroundType == Graphic3d_TOB_TEXTURE)
99   {
100     // Drawing background gradient if:
101     // - gradient fill type is not Aspect_GFM_NONE and
102     // - either background texture is no specified or it is drawn in Aspect_FM_CENTERED mode
103     if (myBackgrounds[Graphic3d_TOB_GRADIENT]->IsDefined()
104       && (!myTextureParams->Aspect()->ToMapTexture()
105         || myBackgrounds[Graphic3d_TOB_TEXTURE]->TextureFillMethod() == Aspect_FM_CENTERED
106         || myBackgrounds[Graphic3d_TOB_TEXTURE]->TextureFillMethod() == Aspect_FM_NONE))
107     {
108       myBackgrounds[Graphic3d_TOB_GRADIENT]->Render(theWorkspace, theProjection);
109     }
110
111     // Drawing background image if it is defined
112     // (texture is defined and fill type is not Aspect_FM_NONE)
113     if (myBackgrounds[Graphic3d_TOB_TEXTURE]->IsDefined()
114       && myTextureParams->Aspect()->ToMapTexture())
115     {
116       aCtx->core11fwd->glDisable (GL_BLEND);
117
118       const OpenGl_Aspects* anOldAspectFace = theWorkspace->SetAspects (myTextureParams);
119       myBackgrounds[Graphic3d_TOB_TEXTURE]->Render (theWorkspace, theProjection);
120       theWorkspace->SetAspects (anOldAspectFace);
121     }
122   }
123
124   if (wasUsedZBuffer)
125   {
126     theWorkspace->SetUseZBuffer (Standard_True);
127     aCtx->core11fwd->glEnable (GL_DEPTH_TEST);
128   }
129 }
130
131 //=======================================================================
132 //function : prepareFrameBuffers
133 //purpose  :
134 //=======================================================================
135 bool OpenGl_View::prepareFrameBuffers (Graphic3d_Camera::Projection& theProj)
136 {
137   theProj = myCamera->ProjectionType();
138   const Handle(OpenGl_Context)& aCtx = myWorkspace->GetGlContext();
139
140   Standard_Integer aSizeX = 0, aSizeY = 0;
141   OpenGl_FrameBuffer* aFrameBuffer = myFBO.get();
142   if (aFrameBuffer != NULL)
143   {
144     aSizeX = aFrameBuffer->GetVPSizeX();
145     aSizeY = aFrameBuffer->GetVPSizeY();
146   }
147   else if (IsActiveXR())
148   {
149     aSizeX = myXRSession->RecommendedViewport().x();
150     aSizeY = myXRSession->RecommendedViewport().y();
151   }
152   else
153   {
154     aSizeX = myWindow->Width();
155     aSizeY = myWindow->Height();
156   }
157
158   const Standard_Integer aRendSizeX = Standard_Integer(myRenderParams.RenderResolutionScale * aSizeX + 0.5f);
159   const Standard_Integer aRendSizeY = Standard_Integer(myRenderParams.RenderResolutionScale * aSizeY + 0.5f);
160   if (aSizeX < 1
161    || aSizeY < 1
162    || aRendSizeX < 1
163    || aRendSizeY < 1)
164   {
165     myBackBufferRestored = Standard_False;
166     myIsImmediateDrawn   = Standard_False;
167     return false;
168   }
169
170   // determine multisampling parameters
171   Standard_Integer aNbSamples = !myToDisableMSAA && aSizeX == aRendSizeX
172                               ? Max (Min (myRenderParams.NbMsaaSamples, aCtx->MaxMsaaSamples()), 0)
173                               : 0;
174   if (aNbSamples != 0)
175   {
176     aNbSamples = OpenGl_Context::GetPowerOfTwo (aNbSamples, aCtx->MaxMsaaSamples());
177   }
178
179   bool toUseOit = myRenderParams.TransparencyMethod == Graphic3d_RTM_BLEND_OIT
180                && checkOitCompatibility (aCtx, aNbSamples > 0);
181
182   const bool toInitImmediateFbo = myTransientDrawToFront
183                                && (!aCtx->caps->useSystemBuffer || (toUseOit && HasImmediateStructures()));
184
185   if ( aFrameBuffer == NULL
186    && !aCtx->DefaultFrameBuffer().IsNull()
187    &&  aCtx->DefaultFrameBuffer()->IsValid())
188   {
189     aFrameBuffer = aCtx->DefaultFrameBuffer().operator->();
190   }
191
192   if (myHasFboBlit
193    && (myTransientDrawToFront
194     || theProj == Graphic3d_Camera::Projection_Stereo
195     || aNbSamples != 0
196     || toUseOit
197     || aSizeX != aRendSizeX))
198   {
199     if (myMainSceneFbos[0]->GetVPSizeX() != aRendSizeX
200      || myMainSceneFbos[0]->GetVPSizeY() != aRendSizeY
201      || myMainSceneFbos[0]->NbSamples()  != aNbSamples)
202     {
203       if (!myTransientDrawToFront)
204       {
205         myImmediateSceneFbos[0]->Release (aCtx.operator->());
206         myImmediateSceneFbos[1]->Release (aCtx.operator->());
207         myImmediateSceneFbos[0]->ChangeViewport (0, 0);
208         myImmediateSceneFbos[1]->ChangeViewport (0, 0);
209       }
210
211       // prepare FBOs containing main scene
212       // for further blitting and rendering immediate presentations on top
213       if (aCtx->core20fwd != NULL)
214       {
215         const bool wasFailedMain0 = checkWasFailedFbo (myMainSceneFbos[0], aRendSizeX, aRendSizeY, aNbSamples);
216         if (!myMainSceneFbos[0]->Init (aCtx, aRendSizeX, aRendSizeY, myFboColorFormat, myFboDepthFormat, aNbSamples)
217          && !wasFailedMain0)
218         {
219           TCollection_ExtendedString aMsg = TCollection_ExtendedString() + "Error! Main FBO "
220                                           + printFboFormat (myMainSceneFbos[0]) + " initialization has failed";
221           aCtx->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, aMsg);
222         }
223       }
224     }
225     if (myMainSceneFbos[0]->IsValid() && (toInitImmediateFbo || myImmediateSceneFbos[0]->IsValid()))
226     {
227       const bool wasFailedImm0 = checkWasFailedFbo (myImmediateSceneFbos[0], myMainSceneFbos[0]);
228       if (!myImmediateSceneFbos[0]->InitLazy (aCtx, *myMainSceneFbos[0])
229        && !wasFailedImm0)
230       {
231         TCollection_ExtendedString aMsg = TCollection_ExtendedString() + "Error! Immediate FBO "
232                                         + printFboFormat (myImmediateSceneFbos[0]) + " initialization has failed";
233         aCtx->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, aMsg);
234       }
235     }
236   }
237   else
238   {
239     myMainSceneFbos     [0]->Release (aCtx.operator->());
240     myMainSceneFbos     [1]->Release (aCtx.operator->());
241     myImmediateSceneFbos[0]->Release (aCtx.operator->());
242     myImmediateSceneFbos[1]->Release (aCtx.operator->());
243     myXrSceneFbo           ->Release (aCtx.operator->());
244     myMainSceneFbos     [0]->ChangeViewport (0, 0);
245     myMainSceneFbos     [1]->ChangeViewport (0, 0);
246     myImmediateSceneFbos[0]->ChangeViewport (0, 0);
247     myImmediateSceneFbos[1]->ChangeViewport (0, 0);
248     myXrSceneFbo           ->ChangeViewport (0, 0);
249   }
250
251   bool hasXRBlitFbo = false;
252   if (theProj == Graphic3d_Camera::Projection_Stereo
253    && IsActiveXR()
254    && myMainSceneFbos[0]->IsValid())
255   {
256     if (aNbSamples != 0
257      || aSizeX != aRendSizeX)
258     {
259       hasXRBlitFbo = myXrSceneFbo->InitLazy (aCtx, aSizeX, aSizeY, myFboColorFormat, myFboDepthFormat, 0);
260       if (!hasXRBlitFbo)
261       {
262         TCollection_ExtendedString aMsg = TCollection_ExtendedString() + "Error! VR FBO "
263                                         + printFboFormat (myXrSceneFbo) + " initialization has failed";
264         aCtx->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, aMsg);
265       }
266     }
267   }
268   else if (theProj == Graphic3d_Camera::Projection_Stereo
269         && myMainSceneFbos[0]->IsValid())
270   {
271     const bool wasFailedMain1 = checkWasFailedFbo (myMainSceneFbos[1], myMainSceneFbos[0]);
272     if (!myMainSceneFbos[1]->InitLazy (aCtx, *myMainSceneFbos[0])
273      && !wasFailedMain1)
274     {
275       TCollection_ExtendedString aMsg = TCollection_ExtendedString() + "Error! Main FBO (second) "
276                                       + printFboFormat (myMainSceneFbos[1]) + " initialization has failed";
277       aCtx->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, aMsg);
278     }
279     if (!myMainSceneFbos[1]->IsValid())
280     {
281       // no enough memory?
282       theProj = Graphic3d_Camera::Projection_Perspective;
283     }
284     else if (!myTransientDrawToFront)
285     {
286       //
287     }
288     else if (!aCtx->HasStereoBuffers()
289            || myRenderParams.StereoMode != Graphic3d_StereoMode_QuadBuffer)
290     {
291       const bool wasFailedImm0 = checkWasFailedFbo (myImmediateSceneFbos[0], myMainSceneFbos[0]);
292       const bool wasFailedImm1 = checkWasFailedFbo (myImmediateSceneFbos[1], myMainSceneFbos[0]);
293       if (!myImmediateSceneFbos[0]->InitLazy (aCtx, *myMainSceneFbos[0])
294        && !wasFailedImm0)
295       {
296         TCollection_ExtendedString aMsg = TCollection_ExtendedString() + "Error! Immediate FBO (first) "
297                                         + printFboFormat (myImmediateSceneFbos[0]) + " initialization has failed";
298         aCtx->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, aMsg);
299       }
300       if (!myImmediateSceneFbos[1]->InitLazy (aCtx, *myMainSceneFbos[0])
301        && !wasFailedImm1)
302       {
303         TCollection_ExtendedString aMsg = TCollection_ExtendedString() + "Error! Immediate FBO (first) "
304                                         + printFboFormat (myImmediateSceneFbos[1]) + " initialization has failed";
305         aCtx->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, aMsg);
306       }
307       if (!myImmediateSceneFbos[0]->IsValid()
308        || !myImmediateSceneFbos[1]->IsValid())
309       {
310         theProj = Graphic3d_Camera::Projection_Perspective;
311       }
312     }
313   }
314   if (!hasXRBlitFbo)
315   {
316     myXrSceneFbo->Release (aCtx.get());
317     myXrSceneFbo->ChangeViewport (0, 0);
318   }
319
320   // process PBR environment
321   if (myShadingModel == Graphic3d_TOSM_PBR
322    || myShadingModel == Graphic3d_TOSM_PBR_FACET)
323   {
324     if (!myPBREnvironment.IsNull()
325       && myPBREnvironment->SizesAreDifferent (myRenderParams.PbrEnvPow2Size,
326                                               myRenderParams.PbrEnvSpecMapNbLevels))
327     {
328       myPBREnvironment->Release (aCtx.get());
329       myPBREnvironment.Nullify();
330       myPBREnvState = OpenGl_PBREnvState_NONEXISTENT;
331       myPBREnvRequest = OpenGl_PBREnvRequest_BAKE;
332       ++myLightsRevision;
333     }
334
335     if (myPBREnvState == OpenGl_PBREnvState_NONEXISTENT
336      && aCtx->HasPBR())
337     {
338       myPBREnvironment = OpenGl_PBREnvironment::Create (aCtx, myRenderParams.PbrEnvPow2Size, myRenderParams.PbrEnvSpecMapNbLevels);
339       myPBREnvState = myPBREnvironment.IsNull() ? OpenGl_PBREnvState_UNAVAILABLE : OpenGl_PBREnvState_CREATED;
340       if (myPBREnvState == OpenGl_PBREnvState_CREATED)
341       {
342         Handle(OpenGl_Texture) anEnvLUT;
343         static const TCollection_AsciiString THE_SHARED_ENV_LUT_KEY("EnvLUT");
344         if (!aCtx->GetResource (THE_SHARED_ENV_LUT_KEY, anEnvLUT))
345         {
346           Handle(Graphic3d_TextureParams) aParams = new Graphic3d_TextureParams();
347           aParams->SetFilter (Graphic3d_TOTF_BILINEAR);
348           aParams->SetRepeat (Standard_False);
349           aParams->SetTextureUnit (aCtx->PBREnvLUTTexUnit());
350           anEnvLUT = new OpenGl_Texture(THE_SHARED_ENV_LUT_KEY, aParams);
351           Handle(Image_PixMap) aPixMap = new Image_PixMap();
352           aPixMap->InitWrapper (Image_Format_RGF, (Standard_Byte*)Textures_EnvLUT, Textures_EnvLUTSize, Textures_EnvLUTSize);
353           OpenGl_TextureFormat aTexFormat = OpenGl_TextureFormat::FindFormat (aCtx, aPixMap->Format(), false);
354         #if defined(GL_ES_VERSION_2_0)
355           // GL_RG32F is not texture-filterable format on OpenGL ES without OES_texture_float_linear extension.
356           // GL_RG16F is texture-filterable since OpenGL ES 3.0 and can be initialized from 32-bit floats.
357           // Note that it is expected that GL_RG16F has enough precision for this table, so that it can be used also on desktop OpenGL.
358           //if (!aCtx->hasTexFloatLinear)
359           aTexFormat.SetInternalFormat (GL_RG16F);
360         #endif
361           if (!aTexFormat.IsValid()
362            || !anEnvLUT->Init (aCtx, aTexFormat, Graphic3d_Vec2i((Standard_Integer)Textures_EnvLUTSize), Graphic3d_TOT_2D, aPixMap.get()))
363           {
364             aCtx->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, "Failed allocation of LUT for PBR");
365             anEnvLUT.Nullify();
366           }
367           aCtx->ShareResource (THE_SHARED_ENV_LUT_KEY, anEnvLUT);
368         }
369         if (!anEnvLUT.IsNull())
370         {
371           anEnvLUT->Bind (aCtx);
372         }
373         myWorkspace->ApplyAspects();
374       }
375     }
376     processPBREnvRequest (aCtx);
377   }
378
379   // create color and coverage accumulation buffers required for OIT algorithm
380   if (toUseOit)
381   {
382     Standard_Integer anFboIt = 0;
383     for (; anFboIt < 2; ++anFboIt)
384     {
385       Handle(OpenGl_FrameBuffer)& aMainSceneFbo          = myMainSceneFbos        [anFboIt];
386       Handle(OpenGl_FrameBuffer)& aMainSceneFboOit       = myMainSceneFbosOit     [anFboIt];
387       Handle(OpenGl_FrameBuffer)& anImmediateSceneFbo    = myImmediateSceneFbos   [anFboIt];
388       Handle(OpenGl_FrameBuffer)& anImmediateSceneFboOit = myImmediateSceneFbosOit[anFboIt];
389       if (aMainSceneFbo->IsValid()
390        && (aMainSceneFboOit->GetVPSizeX() != aRendSizeX
391         || aMainSceneFboOit->GetVPSizeY() != aRendSizeY
392         || aMainSceneFboOit->NbSamples()  != aNbSamples))
393       {
394         Standard_Integer aColorConfig = 0;
395         for (;;) // seemly responding to driver limitation (GL_FRAMEBUFFER_UNSUPPORTED)
396         {
397           if (myFboOitColorConfig.IsEmpty())
398           {
399             if (!chooseOitColorConfiguration (aCtx, aColorConfig++, myFboOitColorConfig))
400             {
401               break;
402             }
403           }
404           if (aMainSceneFboOit->Init (aCtx, aRendSizeX, aRendSizeY, myFboOitColorConfig, aMainSceneFbo->DepthStencilTexture(), aNbSamples))
405           {
406             break;
407           }
408           myFboOitColorConfig.Clear();
409         }
410         if (!aMainSceneFboOit->IsValid())
411         {
412           break;
413         }
414       }
415       else if (!aMainSceneFbo->IsValid())
416       {
417         aMainSceneFboOit->Release (aCtx.operator->());
418         aMainSceneFboOit->ChangeViewport (0, 0);
419       }
420
421       if (anImmediateSceneFbo->IsValid()
422        && (anImmediateSceneFboOit->GetVPSizeX() != aRendSizeX
423         || anImmediateSceneFboOit->GetVPSizeY() != aRendSizeY
424         || anImmediateSceneFboOit->NbSamples()  != aNbSamples))
425       {
426         if (!anImmediateSceneFboOit->Init (aCtx, aRendSizeX, aRendSizeY, myFboOitColorConfig,
427                                            anImmediateSceneFbo->DepthStencilTexture(), aNbSamples))
428         {
429           break;
430         }
431       }
432       else if (!anImmediateSceneFbo->IsValid())
433       {
434         anImmediateSceneFboOit->Release (aCtx.operator->());
435         anImmediateSceneFboOit->ChangeViewport (0, 0);
436       }
437     }
438     if (anFboIt == 0) // only the first OIT framebuffer is mandatory
439     {
440       aCtx->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH,
441                          "Initialization of float texture framebuffer for use with\n"
442                          "  blended order-independent transparency rendering algorithm has failed.\n"
443                          "  Blended order-independent transparency will not be available.\n");
444       if (aNbSamples > 0)
445       {
446         myToDisableOITMSAA = Standard_True;
447       }
448       else
449       {
450         myToDisableOIT     = Standard_True;
451       }
452       toUseOit = false;
453     }
454   }
455   if (!toUseOit && myMainSceneFbosOit[0]->IsValid())
456   {
457     myMainSceneFbosOit     [0]->Release (aCtx.operator->());
458     myMainSceneFbosOit     [1]->Release (aCtx.operator->());
459     myImmediateSceneFbosOit[0]->Release (aCtx.operator->());
460     myImmediateSceneFbosOit[1]->Release (aCtx.operator->());
461     myMainSceneFbosOit     [0]->ChangeViewport (0, 0);
462     myMainSceneFbosOit     [1]->ChangeViewport (0, 0);
463     myImmediateSceneFbosOit[0]->ChangeViewport (0, 0);
464     myImmediateSceneFbosOit[1]->ChangeViewport (0, 0);
465   }
466
467   return true;
468 }
469
470 //=======================================================================
471 //function : Redraw
472 //purpose  :
473 //=======================================================================
474 void OpenGl_View::Redraw()
475 {
476   const Standard_Boolean wasDisabledMSAA = myToDisableMSAA;
477   const Standard_Boolean hadFboBlit      = myHasFboBlit;
478   if (myRenderParams.Method == Graphic3d_RM_RAYTRACING
479   && !myCaps->vboDisable
480   && !myCaps->keepArrayData)
481   {
482     // caps are shared across all views, thus we need to invalidate all of them
483     // if (myWasRedrawnGL) { myStructureManager->SetDeviceLost(); }
484     myDriver->setDeviceLost();
485     myCaps->keepArrayData = Standard_True;
486   }
487
488   if (!myWorkspace->Activate())
489   {
490     return;
491   }
492
493   // implicitly disable VSync when using HMD composer (can be mirrored in window for debugging)
494   myWindow->SetSwapInterval (IsActiveXR());
495
496   ++myFrameCounter;
497   const Handle(OpenGl_Context)& aCtx = myWorkspace->GetGlContext();
498   aCtx->FrameStats()->FrameStart (myWorkspace->View(), false);
499   aCtx->SetLineFeather (myRenderParams.LineFeather);
500
501   const Standard_Integer anSRgbState = aCtx->ToRenderSRGB() ? 1 : 0;
502   if (mySRgbState != -1
503    && mySRgbState != anSRgbState)
504   {
505     releaseSrgbResources (aCtx);
506     initTextureEnv (aCtx);
507   }
508   mySRgbState = anSRgbState;
509   aCtx->ShaderManager()->UpdateSRgbState();
510
511   // release pending GL resources
512   aCtx->ReleaseDelayed();
513
514   // fetch OpenGl context state
515   aCtx->FetchState();
516
517   const Graphic3d_StereoMode   aStereoMode  = myRenderParams.StereoMode;
518   Graphic3d_Camera::Projection aProjectType = myCamera->ProjectionType();
519   if (!prepareFrameBuffers (aProjectType))
520   {
521     myBackBufferRestored = Standard_False;
522     myIsImmediateDrawn   = Standard_False;
523     return;
524   }
525
526   OpenGl_FrameBuffer* aFrameBuffer = myFBO.get();
527   bool toSwap = aCtx->IsRender()
528             && !aCtx->caps->buffersNoSwap
529             &&  aFrameBuffer == NULL
530             &&  (!IsActiveXR() || myRenderParams.ToMirrorComposer);
531   if ( aFrameBuffer == NULL
532    && !aCtx->DefaultFrameBuffer().IsNull()
533    &&  aCtx->DefaultFrameBuffer()->IsValid())
534   {
535     aFrameBuffer = aCtx->DefaultFrameBuffer().operator->();
536   }
537
538   if (aProjectType == Graphic3d_Camera::Projection_Stereo)
539   {
540     OpenGl_FrameBuffer* aMainFbos[2] =
541     {
542       myMainSceneFbos[0]->IsValid() ? myMainSceneFbos[0].operator->() : NULL,
543       myMainSceneFbos[1]->IsValid() ? myMainSceneFbos[1].operator->() : NULL
544     };
545     OpenGl_FrameBuffer* aMainFbosOit[2] =
546     {
547       myMainSceneFbosOit[0]->IsValid() ? myMainSceneFbosOit[0].operator->() : NULL,
548       myMainSceneFbosOit[1]->IsValid() ? myMainSceneFbosOit[1].operator->() :
549         myMainSceneFbosOit[0]->IsValid() ? myMainSceneFbosOit[0].operator->() : NULL
550     };
551
552     OpenGl_FrameBuffer* anImmFbos[2] =
553     {
554       myImmediateSceneFbos[0]->IsValid() ? myImmediateSceneFbos[0].operator->() : NULL,
555       myImmediateSceneFbos[1]->IsValid() ? myImmediateSceneFbos[1].operator->() : NULL
556     };
557     OpenGl_FrameBuffer* anImmFbosOit[2] =
558     {
559       myImmediateSceneFbosOit[0]->IsValid() ? myImmediateSceneFbosOit[0].operator->() : NULL,
560       myImmediateSceneFbosOit[1]->IsValid() ? myImmediateSceneFbosOit[1].operator->() :
561         myImmediateSceneFbosOit[0]->IsValid() ? myImmediateSceneFbosOit[0].operator->() : NULL
562     };
563
564     if (IsActiveXR())
565     {
566       // use single frame for both views - caching main scene content makes no sense
567       // when head position is expected to be updated each frame redraw with high accuracy
568       aMainFbos[1]    = aMainFbos[0];
569       aMainFbosOit[1] = aMainFbosOit[0];
570       anImmFbos[0]    = aMainFbos[0];
571       anImmFbos[1]    = aMainFbos[1];
572       anImmFbosOit[0] = aMainFbosOit[0];
573       anImmFbosOit[1] = aMainFbosOit[1];
574     }
575     else if (!myTransientDrawToFront)
576     {
577       anImmFbos   [0] = aMainFbos   [0];
578       anImmFbos   [1] = aMainFbos   [1];
579       anImmFbosOit[0] = aMainFbosOit[0];
580       anImmFbosOit[1] = aMainFbosOit[1];
581     }
582     else if (aStereoMode == Graphic3d_StereoMode_SoftPageFlip
583           || aStereoMode == Graphic3d_StereoMode_QuadBuffer)
584     {
585       anImmFbos   [0] = NULL;
586       anImmFbos   [1] = NULL;
587       anImmFbosOit[0] = NULL;
588       anImmFbosOit[1] = NULL;
589     }
590
591   #if !defined(GL_ES_VERSION_2_0)
592     aCtx->SetReadDrawBuffer (aStereoMode == Graphic3d_StereoMode_QuadBuffer ? GL_BACK_LEFT : GL_BACK);
593   #endif
594     aCtx->SetResolution (myRenderParams.Resolution, myRenderParams.ResolutionRatio(),
595                          aMainFbos[0] != NULL ? myRenderParams.RenderResolutionScale : 1.0f);
596
597     redraw (Graphic3d_Camera::Projection_MonoLeftEye, aMainFbos[0], aMainFbosOit[0]);
598     myBackBufferRestored = Standard_True;
599     myIsImmediateDrawn   = Standard_False;
600   #if !defined(GL_ES_VERSION_2_0)
601     aCtx->SetReadDrawBuffer (aStereoMode == Graphic3d_StereoMode_QuadBuffer ? GL_BACK_LEFT : GL_BACK);
602   #endif
603     aCtx->SetResolution (myRenderParams.Resolution, myRenderParams.ResolutionRatio(),
604                          anImmFbos[0] != NULL ? myRenderParams.RenderResolutionScale : 1.0f);
605     if (!redrawImmediate (Graphic3d_Camera::Projection_MonoLeftEye, aMainFbos[0], anImmFbos[0], anImmFbosOit[0]))
606     {
607       toSwap = false;
608     }
609     else if (aStereoMode == Graphic3d_StereoMode_SoftPageFlip && toSwap)
610     {
611       aCtx->SwapBuffers();
612     }
613
614     if (IsActiveXR())
615     {
616       // push Left frame to HMD display composer
617       OpenGl_FrameBuffer* anXRFbo = myXrSceneFbo->IsValid() ? myXrSceneFbo.get() : aMainFbos[0];
618       if (anXRFbo != aMainFbos[0])
619       {
620         blitBuffers (aMainFbos[0], anXRFbo); // resize or resolve MSAA samples
621       }
622     #if !defined(GL_ES_VERSION_2_0)
623       const Aspect_GraphicsLibrary aGraphicsLib = Aspect_GraphicsLibrary_OpenGL;
624     #else
625       const Aspect_GraphicsLibrary aGraphicsLib = Aspect_GraphicsLibrary_OpenGLES;
626     #endif
627       myXRSession->SubmitEye ((void* )(size_t )anXRFbo->ColorTexture()->TextureId(),
628                               aGraphicsLib, Aspect_ColorSpace_sRGB, Aspect_Eye_Left);
629     }
630
631   #if !defined(GL_ES_VERSION_2_0)
632     aCtx->SetReadDrawBuffer (aStereoMode == Graphic3d_StereoMode_QuadBuffer ? GL_BACK_RIGHT : GL_BACK);
633   #endif
634     aCtx->SetResolution (myRenderParams.Resolution, myRenderParams.ResolutionRatio(),
635                          aMainFbos[1] != NULL ? myRenderParams.RenderResolutionScale : 1.0f);
636
637     redraw (Graphic3d_Camera::Projection_MonoRightEye, aMainFbos[1], aMainFbosOit[1]);
638     myBackBufferRestored = Standard_True;
639     myIsImmediateDrawn   = Standard_False;
640     aCtx->SetResolution (myRenderParams.Resolution, myRenderParams.ResolutionRatio(),
641                          anImmFbos[1] != NULL ? myRenderParams.RenderResolutionScale : 1.0f);
642     if (!redrawImmediate (Graphic3d_Camera::Projection_MonoRightEye, aMainFbos[1], anImmFbos[1], anImmFbosOit[1]))
643     {
644       toSwap = false;
645     }
646
647     if (IsActiveXR())
648     {
649       // push Right frame to HMD display composer
650       OpenGl_FrameBuffer* anXRFbo = myXrSceneFbo->IsValid() ? myXrSceneFbo.get() : aMainFbos[1];
651       if (anXRFbo != aMainFbos[1])
652       {
653         blitBuffers (aMainFbos[1], anXRFbo); // resize or resolve MSAA samples
654       }
655     #if !defined(GL_ES_VERSION_2_0)
656       const Aspect_GraphicsLibrary aGraphicsLib = Aspect_GraphicsLibrary_OpenGL;
657     #else
658       const Aspect_GraphicsLibrary aGraphicsLib = Aspect_GraphicsLibrary_OpenGLES;
659     #endif
660       myXRSession->SubmitEye ((void* )(size_t )anXRFbo->ColorTexture()->TextureId(),
661                               aGraphicsLib, Aspect_ColorSpace_sRGB, Aspect_Eye_Right);
662       ::glFinish();
663
664       if (myRenderParams.ToMirrorComposer)
665       {
666         blitBuffers (anXRFbo, aFrameBuffer, myToFlipOutput);
667       }
668     }
669     else if (anImmFbos[0] != NULL)
670     {
671       aCtx->SetResolution (myRenderParams.Resolution, myRenderParams.ResolutionRatio(), 1.0f);
672       drawStereoPair (aFrameBuffer);
673     }
674   }
675   else
676   {
677     OpenGl_FrameBuffer* aMainFbo    = myMainSceneFbos[0]->IsValid() ? myMainSceneFbos[0].operator->() : aFrameBuffer;
678     OpenGl_FrameBuffer* aMainFboOit = myMainSceneFbosOit[0]->IsValid() ? myMainSceneFbosOit[0].operator->() : NULL;
679     OpenGl_FrameBuffer* anImmFbo    = aFrameBuffer;
680     OpenGl_FrameBuffer* anImmFboOit = NULL;
681     if (!myTransientDrawToFront)
682     {
683       anImmFbo    = aMainFbo;
684       anImmFboOit = aMainFboOit;
685     }
686     else if (myImmediateSceneFbos[0]->IsValid())
687     {
688       anImmFbo    = myImmediateSceneFbos[0].operator->();
689       anImmFboOit = myImmediateSceneFbosOit[0]->IsValid() ? myImmediateSceneFbosOit[0].operator->() : NULL;
690     }
691
692   #if !defined(GL_ES_VERSION_2_0)
693     if (aMainFbo == NULL)
694     {
695       aCtx->SetReadDrawBuffer (GL_BACK);
696     }
697   #endif
698     aCtx->SetResolution (myRenderParams.Resolution, myRenderParams.ResolutionRatio(),
699                          aMainFbo != aFrameBuffer ? myRenderParams.RenderResolutionScale : 1.0f);
700
701     redraw (aProjectType, aMainFbo, aMainFboOit);
702     myBackBufferRestored = Standard_True;
703     myIsImmediateDrawn   = Standard_False;
704     aCtx->SetResolution (myRenderParams.Resolution, myRenderParams.ResolutionRatio(),
705                          anImmFbo != aFrameBuffer ? myRenderParams.RenderResolutionScale : 1.0f);
706     if (!redrawImmediate (aProjectType, aMainFbo, anImmFbo, anImmFboOit))
707     {
708       toSwap = false;
709     }
710
711     if (anImmFbo != NULL
712      && anImmFbo != aFrameBuffer)
713     {
714       blitBuffers (anImmFbo, aFrameBuffer, myToFlipOutput);
715     }
716   }
717
718   if (myRenderParams.Method == Graphic3d_RM_RAYTRACING
719    && myRenderParams.IsGlobalIlluminationEnabled)
720   {
721     myAccumFrames++;
722   }
723
724   // bind default FBO
725   bindDefaultFbo();
726
727   if (wasDisabledMSAA != myToDisableMSAA
728    || hadFboBlit      != myHasFboBlit)
729   {
730     // retry on error
731     Redraw();
732   }
733
734   // reset state for safety
735   aCtx->BindProgram (Handle(OpenGl_ShaderProgram)());
736   if (aCtx->caps->ffpEnable)
737   {
738     aCtx->ShaderManager()->PushState (Handle(OpenGl_ShaderProgram)());
739   }
740
741   // Swap the buffers
742   if (toSwap)
743   {
744     aCtx->SwapBuffers();
745     if (!myMainSceneFbos[0]->IsValid())
746     {
747       myBackBufferRestored = Standard_False;
748     }
749   }
750   else
751   {
752     aCtx->core11fwd->glFlush();
753   }
754
755   // reset render mode state
756   aCtx->FetchState();
757   aCtx->FrameStats()->FrameEnd (myWorkspace->View(), false);
758
759   myWasRedrawnGL = Standard_True;
760 }
761
762 // =======================================================================
763 // function : RedrawImmediate
764 // purpose  :
765 // =======================================================================
766 void OpenGl_View::RedrawImmediate()
767 {
768   if (!myWorkspace->Activate())
769     return;
770
771   // no special handling of HMD display, since it will force full Redraw() due to no frame caching (myBackBufferRestored)
772   Handle(OpenGl_Context) aCtx = myWorkspace->GetGlContext();
773   if (!myTransientDrawToFront
774    || !myBackBufferRestored
775    || (aCtx->caps->buffersNoSwap && !myMainSceneFbos[0]->IsValid()))
776   {
777     Redraw();
778     return;
779   }
780
781   const Graphic3d_StereoMode   aStereoMode  = myRenderParams.StereoMode;
782   Graphic3d_Camera::Projection aProjectType = myCamera->ProjectionType();
783   OpenGl_FrameBuffer*          aFrameBuffer = myFBO.get();
784   aCtx->FrameStats()->FrameStart (myWorkspace->View(), true);
785
786   if ( aFrameBuffer == NULL
787    && !aCtx->DefaultFrameBuffer().IsNull()
788    &&  aCtx->DefaultFrameBuffer()->IsValid())
789   {
790     aFrameBuffer = aCtx->DefaultFrameBuffer().operator->();
791   }
792
793   if (aProjectType == Graphic3d_Camera::Projection_Stereo)
794   {
795     if (myMainSceneFbos[0]->IsValid()
796     && !myMainSceneFbos[1]->IsValid())
797     {
798       aProjectType = Graphic3d_Camera::Projection_Perspective;
799     }
800   }
801
802   bool toSwap = false;
803   if (aProjectType == Graphic3d_Camera::Projection_Stereo)
804   {
805     OpenGl_FrameBuffer* aMainFbos[2] =
806     {
807       myMainSceneFbos[0]->IsValid() ? myMainSceneFbos[0].operator->() : NULL,
808       myMainSceneFbos[1]->IsValid() ? myMainSceneFbos[1].operator->() : NULL
809     };
810     OpenGl_FrameBuffer* anImmFbos[2] =
811     {
812       myImmediateSceneFbos[0]->IsValid() ? myImmediateSceneFbos[0].operator->() : NULL,
813       myImmediateSceneFbos[1]->IsValid() ? myImmediateSceneFbos[1].operator->() : NULL
814     };
815     OpenGl_FrameBuffer* anImmFbosOit[2] =
816     {
817       myImmediateSceneFbosOit[0]->IsValid() ? myImmediateSceneFbosOit[0].operator->() : NULL,
818       myImmediateSceneFbosOit[1]->IsValid() ? myImmediateSceneFbosOit[1].operator->() :
819         myImmediateSceneFbosOit[0]->IsValid() ? myImmediateSceneFbosOit[0].operator->() : NULL
820     };
821     if (aStereoMode == Graphic3d_StereoMode_SoftPageFlip
822      || aStereoMode == Graphic3d_StereoMode_QuadBuffer)
823     {
824       anImmFbos[0]    = NULL;
825       anImmFbos[1]    = NULL;
826       anImmFbosOit[0] = NULL;
827       anImmFbosOit[1] = NULL;
828     }
829
830     if (aCtx->arbFBO != NULL)
831     {
832       aCtx->arbFBO->glBindFramebuffer (GL_FRAMEBUFFER, OpenGl_FrameBuffer::NO_FRAMEBUFFER);
833     }
834   #if !defined(GL_ES_VERSION_2_0)
835     if (anImmFbos[0] == NULL)
836     {
837       aCtx->SetReadDrawBuffer (aStereoMode == Graphic3d_StereoMode_QuadBuffer ? GL_BACK_LEFT : GL_BACK);
838     }
839   #endif
840
841     aCtx->SetResolution (myRenderParams.Resolution, myRenderParams.ResolutionRatio(),
842                          anImmFbos[0] != NULL ? myRenderParams.RenderResolutionScale : 1.0f);
843     toSwap = redrawImmediate (Graphic3d_Camera::Projection_MonoLeftEye,
844                               aMainFbos[0],
845                               anImmFbos[0],
846                               anImmFbosOit[0],
847                               Standard_True) || toSwap;
848     if (aStereoMode == Graphic3d_StereoMode_SoftPageFlip
849     &&  toSwap
850     && !aCtx->caps->buffersNoSwap)
851     {
852       aCtx->SwapBuffers();
853     }
854
855     if (aCtx->arbFBO != NULL)
856     {
857       aCtx->arbFBO->glBindFramebuffer (GL_FRAMEBUFFER, OpenGl_FrameBuffer::NO_FRAMEBUFFER);
858     }
859   #if !defined(GL_ES_VERSION_2_0)
860     if (anImmFbos[1] == NULL)
861     {
862       aCtx->SetReadDrawBuffer (aStereoMode == Graphic3d_StereoMode_QuadBuffer ? GL_BACK_RIGHT : GL_BACK);
863     }
864   #endif
865     aCtx->SetResolution (myRenderParams.Resolution, myRenderParams.ResolutionRatio(),
866                          anImmFbos[1] != NULL ? myRenderParams.RenderResolutionScale : 1.0f);
867     toSwap = redrawImmediate (Graphic3d_Camera::Projection_MonoRightEye,
868                               aMainFbos[1],
869                               anImmFbos[1],
870                               anImmFbosOit[1],
871                               Standard_True) || toSwap;
872     if (anImmFbos[0] != NULL)
873     {
874       drawStereoPair (aFrameBuffer);
875     }
876   }
877   else
878   {
879     OpenGl_FrameBuffer* aMainFbo = myMainSceneFbos[0]->IsValid() ? myMainSceneFbos[0].operator->() : NULL;
880     OpenGl_FrameBuffer* anImmFbo = aFrameBuffer;
881     OpenGl_FrameBuffer* anImmFboOit = NULL;
882     if (myImmediateSceneFbos[0]->IsValid())
883     {
884       anImmFbo    = myImmediateSceneFbos[0].operator->();
885       anImmFboOit = myImmediateSceneFbosOit[0]->IsValid() ? myImmediateSceneFbosOit[0].operator->() : NULL;
886     }
887   #if !defined(GL_ES_VERSION_2_0)
888     if (aMainFbo == NULL)
889     {
890       aCtx->SetReadDrawBuffer (GL_BACK);
891     }
892   #endif
893     aCtx->SetResolution (myRenderParams.Resolution, myRenderParams.ResolutionRatio(),
894                          anImmFbo != aFrameBuffer ? myRenderParams.RenderResolutionScale : 1.0f);
895     toSwap = redrawImmediate (aProjectType,
896                               aMainFbo,
897                               anImmFbo,
898                               anImmFboOit,
899                               Standard_True) || toSwap;
900     if (anImmFbo != NULL
901      && anImmFbo != aFrameBuffer)
902     {
903       blitBuffers (anImmFbo, aFrameBuffer, myToFlipOutput);
904     }
905   }
906
907   // bind default FBO
908   bindDefaultFbo();
909
910   // reset state for safety
911   aCtx->BindProgram (Handle(OpenGl_ShaderProgram)());
912   if (aCtx->caps->ffpEnable)
913   {
914     aCtx->ShaderManager()->PushState (Handle(OpenGl_ShaderProgram)());
915   }
916
917   if (toSwap && !aCtx->caps->buffersNoSwap)
918   {
919     aCtx->SwapBuffers();
920   }
921   else
922   {
923     aCtx->core11fwd->glFlush();
924   }
925   aCtx->FrameStats()->FrameEnd (myWorkspace->View(), true);
926
927   myWasRedrawnGL = Standard_True;
928 }
929
930 // =======================================================================
931 // function : redraw
932 // purpose  :
933 // =======================================================================
934 void OpenGl_View::redraw (const Graphic3d_Camera::Projection theProjection,
935                           OpenGl_FrameBuffer*                theReadDrawFbo,
936                           OpenGl_FrameBuffer*                theOitAccumFbo)
937 {
938   Handle(OpenGl_Context) aCtx = myWorkspace->GetGlContext();
939   if (theReadDrawFbo != NULL)
940   {
941     theReadDrawFbo->BindBuffer    (aCtx);
942     theReadDrawFbo->SetupViewport (aCtx);
943   }
944   else
945   {
946     const Standard_Integer aViewport[4] = { 0, 0, myWindow->Width(), myWindow->Height() };
947     aCtx->ResizeViewport (aViewport);
948   }
949
950   // request reset of material
951   aCtx->ShaderManager()->UpdateMaterialState();
952
953   myWorkspace->UseZBuffer()    = Standard_True;
954   myWorkspace->UseDepthWrite() = Standard_True;
955   GLbitfield toClear = GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT;
956   aCtx->core11fwd->glDepthFunc (GL_LEQUAL);
957   aCtx->core11fwd->glDepthMask (GL_TRUE);
958   aCtx->core11fwd->glEnable (GL_DEPTH_TEST);
959
960   aCtx->core11fwd->glClearDepth (1.0);
961
962   const OpenGl_Vec4 aBgColor = aCtx->Vec4FromQuantityColor (myBgColor);
963   aCtx->SetColorMaskRGBA (NCollection_Vec4<bool> (true)); // force writes into all components, including alpha
964   aCtx->core11fwd->glClearColor (aBgColor.r(), aBgColor.g(), aBgColor.b(), aCtx->caps->buffersOpaqueAlpha ? 1.0f : 0.0f);
965   aCtx->core11fwd->glClear (toClear);
966   aCtx->SetColorMask (true); // restore default alpha component write state
967
968   render (theProjection, theReadDrawFbo, theOitAccumFbo, Standard_False);
969 }
970
971 // =======================================================================
972 // function : redrawMonoImmediate
973 // purpose  :
974 // =======================================================================
975 bool OpenGl_View::redrawImmediate (const Graphic3d_Camera::Projection theProjection,
976                                    OpenGl_FrameBuffer*                theReadFbo,
977                                    OpenGl_FrameBuffer*                theDrawFbo,
978                                    OpenGl_FrameBuffer*                theOitAccumFbo,
979                                    const Standard_Boolean             theIsPartialUpdate)
980 {
981   const Handle(OpenGl_Context)& aCtx = myWorkspace->GetGlContext();
982   GLboolean toCopyBackToFront = GL_FALSE;
983   if (theDrawFbo == theReadFbo
984    && theDrawFbo != NULL
985    && theDrawFbo->IsValid())
986   {
987     myBackBufferRestored = Standard_False;
988     theDrawFbo->BindBuffer (aCtx);
989   }
990   else if (theReadFbo != NULL
991         && theReadFbo->IsValid()
992         && aCtx->IsRender())
993   {
994     if (!blitBuffers (theReadFbo, theDrawFbo))
995     {
996       return true;
997     }
998   }
999   else if (theDrawFbo == NULL)
1000   {
1001   #if !defined(GL_ES_VERSION_2_0)
1002     aCtx->core11fwd->glGetBooleanv (GL_DOUBLEBUFFER, &toCopyBackToFront);
1003   #endif
1004     if (toCopyBackToFront
1005      && myTransientDrawToFront)
1006     {
1007       if (!HasImmediateStructures()
1008        && !theIsPartialUpdate)
1009       {
1010         // prefer Swap Buffers within Redraw in compatibility mode (without FBO)
1011         return true;
1012       }
1013       if (!copyBackToFront())
1014       {
1015         toCopyBackToFront    = GL_FALSE;
1016         myBackBufferRestored = Standard_False;
1017       }
1018     }
1019     else
1020     {
1021       toCopyBackToFront    = GL_FALSE;
1022       myBackBufferRestored = Standard_False;
1023     }
1024   }
1025   else
1026   {
1027     myBackBufferRestored = Standard_False;
1028   }
1029   myIsImmediateDrawn = Standard_True;
1030
1031   myWorkspace->UseZBuffer()    = Standard_True;
1032   myWorkspace->UseDepthWrite() = Standard_True;
1033   glDepthFunc (GL_LEQUAL);
1034   glDepthMask (GL_TRUE);
1035   glEnable (GL_DEPTH_TEST);
1036 #if !defined(GL_ES_VERSION_2_0)
1037   glClearDepth (1.0);
1038 #else
1039   glClearDepthf (1.0f);
1040 #endif
1041
1042   render (theProjection, theDrawFbo, theOitAccumFbo, Standard_True);
1043
1044   return !toCopyBackToFront;
1045 }
1046
1047 //=======================================================================
1048 //function : Render
1049 //purpose  :
1050 //=======================================================================
1051 void OpenGl_View::render (Graphic3d_Camera::Projection theProjection,
1052                           OpenGl_FrameBuffer*          theOutputFBO,
1053                           OpenGl_FrameBuffer*          theOitAccumFbo,
1054                           const Standard_Boolean       theToDrawImmediate)
1055 {
1056   // ==================================
1057   //      Step 1: Prepare for render
1058   // ==================================
1059
1060   const Handle(OpenGl_Context)& aContext = myWorkspace->GetGlContext();
1061   aContext->SetAllowSampleAlphaToCoverage (myRenderParams.ToEnableAlphaToCoverage
1062                                         && theOutputFBO != NULL
1063                                         && theOutputFBO->NbSamples() != 0);
1064
1065 #if !defined(GL_ES_VERSION_2_0)
1066   // Disable current clipping planes
1067   if (aContext->core11 != NULL)
1068   {
1069     const Standard_Integer aMaxPlanes = aContext->MaxClipPlanes();
1070     for (Standard_Integer aClipPlaneId = GL_CLIP_PLANE0; aClipPlaneId < GL_CLIP_PLANE0 + aMaxPlanes; ++aClipPlaneId)
1071     {
1072       aContext->core11fwd->glDisable (aClipPlaneId);
1073     }
1074   }
1075 #endif
1076
1077   // update states of OpenGl_BVHTreeSelector (frustum culling algorithm);
1078   // note that we pass here window dimensions ignoring Graphic3d_RenderingParams::RenderResolutionScale
1079   myBVHSelector.SetViewVolume (myCamera);
1080   myBVHSelector.SetViewportSize (myWindow->Width(), myWindow->Height(), myRenderParams.ResolutionRatio());
1081   myBVHSelector.CacheClipPtsProjections();
1082
1083   const Handle(OpenGl_ShaderManager)& aManager = aContext->ShaderManager();
1084   const Handle(Graphic3d_LightSet)&   aLights  = myShadingModel == Graphic3d_TOSM_UNLIT ? myNoShadingLight : myLights;
1085   Standard_Size aLightsRevision = 0;
1086   if (!aLights.IsNull())
1087   {
1088     aLightsRevision = aLights->UpdateRevision();
1089   }
1090   if (StateInfo (myCurrLightSourceState, aManager->LightSourceState().Index()) != myLastLightSourceState
1091    || aLightsRevision != myLightsRevision)
1092   {
1093     myLightsRevision = aLightsRevision;
1094     aManager->UpdateLightSourceStateTo (aLights, SpecIBLMapLevels());
1095     myLastLightSourceState = StateInfo (myCurrLightSourceState, aManager->LightSourceState().Index());
1096   }
1097
1098   // Update matrices if camera has changed.
1099   Graphic3d_WorldViewProjState aWVPState = myCamera->WorldViewProjState();
1100   if (myWorldViewProjState != aWVPState)
1101   {
1102     myAccumFrames = 0;
1103     myWorldViewProjState = aWVPState;
1104   }
1105
1106   myLocalOrigin.SetCoord (0.0, 0.0, 0.0);
1107   aContext->SetCamera (myCamera);
1108   if (aManager->ModelWorldState().Index() == 0)
1109   {
1110     aContext->ShaderManager()->UpdateModelWorldStateTo (OpenGl_Mat4());
1111   }
1112
1113   // ====================================
1114   //      Step 2: Redraw background
1115   // ====================================
1116
1117   // Render background
1118   if (!theToDrawImmediate)
1119   {
1120     drawBackground (myWorkspace, theProjection);
1121   }
1122
1123 #if !defined(GL_ES_VERSION_2_0)
1124   // Switch off lighting by default
1125   if (aContext->core11 != NULL
1126    && aContext->caps->ffpEnable)
1127   {
1128     glDisable(GL_LIGHTING);
1129   }
1130 #endif
1131
1132   // =================================
1133   //      Step 3: Redraw main plane
1134   // =================================
1135
1136   // Setup face culling
1137   GLboolean isCullFace = GL_FALSE;
1138   if (myBackfacing != Graphic3d_TOBM_AUTOMATIC)
1139   {
1140     isCullFace = glIsEnabled (GL_CULL_FACE);
1141     if (myBackfacing == Graphic3d_TOBM_DISABLE)
1142     {
1143       glEnable (GL_CULL_FACE);
1144       glCullFace (GL_BACK);
1145     }
1146     else
1147       glDisable (GL_CULL_FACE);
1148   }
1149
1150 #if !defined(GL_ES_VERSION_2_0)
1151   // if the view is scaled normal vectors are scaled to unit
1152   // length for correct displaying of shaded objects
1153   const gp_Pnt anAxialScale = aContext->Camera()->AxialScale();
1154   if (anAxialScale.X() != 1.F ||
1155       anAxialScale.Y() != 1.F ||
1156       anAxialScale.Z() != 1.F)
1157   {
1158     aContext->SetGlNormalizeEnabled (Standard_True);
1159   }
1160   else
1161   {
1162     aContext->SetGlNormalizeEnabled (Standard_False);
1163   }
1164 #endif
1165
1166   aManager->SetShadingModel (OpenGl_ShaderManager::PBRShadingModelFallback (myShadingModel, checkPBRAvailability()));
1167
1168   // Redraw 3d scene
1169   if (theProjection == Graphic3d_Camera::Projection_MonoLeftEye)
1170   {
1171     aContext->ProjectionState.SetCurrent (aContext->Camera()->ProjectionStereoLeftF());
1172     aContext->ApplyProjectionMatrix();
1173   }
1174   else if (theProjection == Graphic3d_Camera::Projection_MonoRightEye)
1175   {
1176     aContext->ProjectionState.SetCurrent (aContext->Camera()->ProjectionStereoRightF());
1177     aContext->ApplyProjectionMatrix();
1178   }
1179
1180   myWorkspace->SetEnvironmentTexture (myTextureEnv);
1181
1182   renderScene (theProjection, theOutputFBO, theOitAccumFbo, theToDrawImmediate);
1183
1184   myWorkspace->SetEnvironmentTexture (Handle(OpenGl_TextureSet)());
1185
1186   // ===============================
1187   //      Step 4: Trihedron
1188   // ===============================
1189
1190   // Resetting GL parameters according to the default aspects
1191   // in order to synchronize GL state with the graphic driver state
1192   // before drawing auxiliary stuff (trihedrons, overlayer)
1193   myWorkspace->ResetAppliedAspect();
1194
1195   // Render trihedron
1196   if (!theToDrawImmediate)
1197   {
1198     renderTrihedron (myWorkspace);
1199
1200     // Restore face culling
1201     if (myBackfacing != Graphic3d_TOBM_AUTOMATIC)
1202     {
1203       if (isCullFace)
1204       {
1205         glEnable (GL_CULL_FACE);
1206         glCullFace (GL_BACK);
1207       }
1208       else
1209         glDisable (GL_CULL_FACE);
1210     }
1211   }
1212   else
1213   {
1214     renderFrameStats();
1215   }
1216
1217   myWorkspace->ResetAppliedAspect();
1218   aContext->SetAllowSampleAlphaToCoverage (false);
1219   aContext->SetSampleAlphaToCoverage (false);
1220
1221   // reset FFP state for safety
1222   aContext->BindProgram (Handle(OpenGl_ShaderProgram)());
1223   if (aContext->caps->ffpEnable)
1224   {
1225     aContext->ShaderManager()->PushState (Handle(OpenGl_ShaderProgram)());
1226   }
1227
1228   // ==============================================================
1229   //      Step 6: Keep shader manager informed about last View
1230   // ==============================================================
1231
1232   if (!aManager.IsNull())
1233   {
1234     aManager->SetLastView (this);
1235   }
1236 }
1237
1238 // =======================================================================
1239 // function : InvalidateBVHData
1240 // purpose  :
1241 // =======================================================================
1242 void OpenGl_View::InvalidateBVHData (const Graphic3d_ZLayerId theLayerId)
1243 {
1244   myZLayers.InvalidateBVHData (theLayerId);
1245 }
1246
1247 //=======================================================================
1248 //function : renderStructs
1249 //purpose  :
1250 //=======================================================================
1251 void OpenGl_View::renderStructs (Graphic3d_Camera::Projection theProjection,
1252                                  OpenGl_FrameBuffer*          theReadDrawFbo,
1253                                  OpenGl_FrameBuffer*          theOitAccumFbo,
1254                                  const Standard_Boolean       theToDrawImmediate)
1255 {
1256   myZLayers.UpdateCulling (myWorkspace, theToDrawImmediate);
1257   if ( myZLayers.NbStructures() <= 0 )
1258     return;
1259
1260   Handle(OpenGl_Context) aCtx = myWorkspace->GetGlContext();
1261   Standard_Boolean toRenderGL = theToDrawImmediate ||
1262     myRenderParams.Method != Graphic3d_RM_RAYTRACING ||
1263     myRaytraceInitStatus == OpenGl_RT_FAIL ||
1264     aCtx->IsFeedback();
1265
1266   if (!toRenderGL)
1267   {
1268     const Standard_Integer aSizeX = theReadDrawFbo != NULL ? theReadDrawFbo->GetVPSizeX() : myWindow->Width();
1269     const Standard_Integer aSizeY = theReadDrawFbo != NULL ? theReadDrawFbo->GetVPSizeY() : myWindow->Height();
1270
1271     toRenderGL = !initRaytraceResources (aSizeX, aSizeY, aCtx)
1272               || !updateRaytraceGeometry (OpenGl_GUM_CHECK, myId, aCtx);
1273
1274     toRenderGL |= !myIsRaytraceDataValid; // if no ray-trace data use OpenGL
1275
1276     if (!toRenderGL)
1277     {
1278       myOpenGlFBO ->InitLazy (aCtx, aSizeX, aSizeY, myFboColorFormat, myFboDepthFormat, 0);
1279
1280       if (theReadDrawFbo != NULL)
1281         theReadDrawFbo->UnbindBuffer (aCtx);
1282
1283       // Prepare preliminary OpenGL output
1284       if (aCtx->arbFBOBlit != NULL)
1285       {
1286         // Render bottom OSD layer
1287         myZLayers.Render (myWorkspace, theToDrawImmediate, OpenGl_LF_Bottom, theReadDrawFbo, theOitAccumFbo);
1288
1289         const Standard_Integer aPrevFilter = myWorkspace->RenderFilter() & ~(Standard_Integer )(OpenGl_RenderFilter_NonRaytraceableOnly);
1290         myWorkspace->SetRenderFilter (aPrevFilter | OpenGl_RenderFilter_NonRaytraceableOnly);
1291         {
1292           if (theReadDrawFbo != NULL)
1293           {
1294             theReadDrawFbo->BindDrawBuffer (aCtx);
1295           }
1296           else
1297           {
1298             aCtx->arbFBO->glBindFramebuffer (GL_DRAW_FRAMEBUFFER, 0);
1299             aCtx->SetFrameBufferSRGB (false);
1300           }
1301
1302           // Render non-polygonal elements in default layer
1303           myZLayers.Render (myWorkspace, theToDrawImmediate, OpenGl_LF_RayTracable, theReadDrawFbo, theOitAccumFbo);
1304         }
1305         myWorkspace->SetRenderFilter (aPrevFilter);
1306       }
1307
1308       if (theReadDrawFbo != NULL)
1309       {
1310         theReadDrawFbo->BindBuffer (aCtx);
1311       }
1312       else
1313       {
1314         aCtx->arbFBO->glBindFramebuffer (GL_FRAMEBUFFER, 0);
1315         aCtx->SetFrameBufferSRGB (false);
1316       }
1317
1318       // Reset OpenGl aspects state to default to avoid enabling of
1319       // backface culling which is not supported in ray-tracing.
1320       myWorkspace->ResetAppliedAspect();
1321
1322       // Ray-tracing polygonal primitive arrays
1323       raytrace (aSizeX, aSizeY, theProjection, theReadDrawFbo, aCtx);
1324
1325       // Render upper (top and topmost) OpenGL layers
1326       myZLayers.Render (myWorkspace, theToDrawImmediate, OpenGl_LF_Upper, theReadDrawFbo, theOitAccumFbo);
1327     }
1328   }
1329
1330   // Redraw 3D scene using OpenGL in standard
1331   // mode or in case of ray-tracing failure
1332   if (toRenderGL)
1333   {
1334     myZLayers.Render (myWorkspace, theToDrawImmediate, OpenGl_LF_All, theReadDrawFbo, theOitAccumFbo);
1335
1336     // Set flag that scene was redrawn by standard pipeline
1337     myWasRedrawnGL = Standard_True;
1338   }
1339 }
1340
1341 //=======================================================================
1342 //function : renderTrihedron
1343 //purpose  :
1344 //=======================================================================
1345 void OpenGl_View::renderTrihedron (const Handle(OpenGl_Workspace) &theWorkspace)
1346 {
1347   if (myToShowGradTrihedron)
1348   {
1349     myGraduatedTrihedron.Render (theWorkspace);
1350   }
1351 }
1352
1353 //=======================================================================
1354 //function : renderFrameStats
1355 //purpose  :
1356 //=======================================================================
1357 void OpenGl_View::renderFrameStats()
1358 {
1359   if (myRenderParams.ToShowStats
1360    && myRenderParams.CollectedStats != Graphic3d_RenderingParams::PerfCounters_NONE)
1361   {
1362     myFrameStatsPrs.Update (myWorkspace);
1363     myFrameStatsPrs.Render (myWorkspace);
1364   }
1365 }
1366
1367 // =======================================================================
1368 // function : Invalidate
1369 // purpose  :
1370 // =======================================================================
1371 void OpenGl_View::Invalidate()
1372 {
1373   myBackBufferRestored = Standard_False;
1374 }
1375
1376 //=======================================================================
1377 //function : renderScene
1378 //purpose  :
1379 //=======================================================================
1380 void OpenGl_View::renderScene (Graphic3d_Camera::Projection theProjection,
1381                                OpenGl_FrameBuffer*          theReadDrawFbo,
1382                                OpenGl_FrameBuffer*          theOitAccumFbo,
1383                                const Standard_Boolean       theToDrawImmediate)
1384 {
1385   const Handle(OpenGl_Context)& aContext = myWorkspace->GetGlContext();
1386
1387   // Specify clipping planes in view transformation space
1388   aContext->ChangeClipping().Reset (myClipPlanes);
1389   if (!myClipPlanes.IsNull()
1390    && !myClipPlanes->IsEmpty())
1391   {
1392     aContext->ShaderManager()->UpdateClippingState();
1393   }
1394
1395   renderStructs (theProjection, theReadDrawFbo, theOitAccumFbo, theToDrawImmediate);
1396   aContext->BindTextures (Handle(OpenGl_TextureSet)(), Handle(OpenGl_ShaderProgram)());
1397
1398   // Apply restored view matrix.
1399   aContext->ApplyWorldViewMatrix();
1400
1401   aContext->ChangeClipping().Reset (Handle(Graphic3d_SequenceOfHClipPlane)());
1402   if (!myClipPlanes.IsNull()
1403    && !myClipPlanes->IsEmpty())
1404   {
1405     aContext->ShaderManager()->RevertClippingState();
1406   }
1407 }
1408
1409 // =======================================================================
1410 // function : bindDefaultFbo
1411 // purpose  :
1412 // =======================================================================
1413 void OpenGl_View::bindDefaultFbo (OpenGl_FrameBuffer* theCustomFbo)
1414 {
1415   Handle(OpenGl_Context) aCtx = myWorkspace->GetGlContext();
1416   OpenGl_FrameBuffer* anFbo = (theCustomFbo != NULL && theCustomFbo->IsValid())
1417                             ?  theCustomFbo
1418                             : (!aCtx->DefaultFrameBuffer().IsNull()
1419                              && aCtx->DefaultFrameBuffer()->IsValid()
1420                               ? aCtx->DefaultFrameBuffer().operator->()
1421                               : NULL);
1422   if (anFbo != NULL)
1423   {
1424     anFbo->BindBuffer (aCtx);
1425     anFbo->SetupViewport (aCtx);
1426   }
1427   else
1428   {
1429   #if !defined(GL_ES_VERSION_2_0)
1430     aCtx->SetReadDrawBuffer (GL_BACK);
1431   #else
1432     if (aCtx->arbFBO != NULL)
1433     {
1434       aCtx->arbFBO->glBindFramebuffer (GL_FRAMEBUFFER, OpenGl_FrameBuffer::NO_FRAMEBUFFER);
1435     }
1436   #endif
1437     const Standard_Integer aViewport[4] = { 0, 0, myWindow->Width(), myWindow->Height() };
1438     aCtx->ResizeViewport (aViewport);
1439   }
1440 }
1441
1442 // =======================================================================
1443 // function : initBlitQuad
1444 // purpose  :
1445 // =======================================================================
1446 OpenGl_VertexBuffer* OpenGl_View::initBlitQuad (const Standard_Boolean theToFlip)
1447 {
1448   OpenGl_VertexBuffer* aVerts = NULL;
1449   if (!theToFlip)
1450   {
1451     aVerts = &myFullScreenQuad;
1452     if (!aVerts->IsValid())
1453     {
1454       OpenGl_Vec4 aQuad[4] =
1455       {
1456         OpenGl_Vec4( 1.0f, -1.0f, 1.0f, 0.0f),
1457         OpenGl_Vec4( 1.0f,  1.0f, 1.0f, 1.0f),
1458         OpenGl_Vec4(-1.0f, -1.0f, 0.0f, 0.0f),
1459         OpenGl_Vec4(-1.0f,  1.0f, 0.0f, 1.0f)
1460       };
1461       aVerts->Init (myWorkspace->GetGlContext(), 4, 4, aQuad[0].GetData());
1462     }
1463   }
1464   else
1465   {
1466     aVerts = &myFullScreenQuadFlip;
1467     if (!aVerts->IsValid())
1468     {
1469       OpenGl_Vec4 aQuad[4] =
1470       {
1471         OpenGl_Vec4( 1.0f, -1.0f, 1.0f, 1.0f),
1472         OpenGl_Vec4( 1.0f,  1.0f, 1.0f, 0.0f),
1473         OpenGl_Vec4(-1.0f, -1.0f, 0.0f, 1.0f),
1474         OpenGl_Vec4(-1.0f,  1.0f, 0.0f, 0.0f)
1475       };
1476       aVerts->Init (myWorkspace->GetGlContext(), 4, 4, aQuad[0].GetData());
1477     }
1478   }
1479   return aVerts;
1480 }
1481
1482 // =======================================================================
1483 // function : blitBuffers
1484 // purpose  :
1485 // =======================================================================
1486 bool OpenGl_View::blitBuffers (OpenGl_FrameBuffer*    theReadFbo,
1487                                OpenGl_FrameBuffer*    theDrawFbo,
1488                                const Standard_Boolean theToFlip)
1489 {
1490   Handle(OpenGl_Context) aCtx = myWorkspace->GetGlContext();
1491   const Standard_Integer aReadSizeX = theReadFbo != NULL ? theReadFbo->GetVPSizeX() : myWindow->Width();
1492   const Standard_Integer aReadSizeY = theReadFbo != NULL ? theReadFbo->GetVPSizeY() : myWindow->Height();
1493   const Standard_Integer aDrawSizeX = theDrawFbo != NULL ? theDrawFbo->GetVPSizeX() : myWindow->Width();
1494   const Standard_Integer aDrawSizeY = theDrawFbo != NULL ? theDrawFbo->GetVPSizeY() : myWindow->Height();
1495   if (theReadFbo == NULL || aCtx->IsFeedback())
1496   {
1497     return false;
1498   }
1499   else if (theReadFbo == theDrawFbo)
1500   {
1501     return true;
1502   }
1503
1504   // clear destination before blitting
1505   if (theDrawFbo != NULL
1506   &&  theDrawFbo->IsValid())
1507   {
1508     theDrawFbo->BindBuffer (aCtx);
1509   }
1510   else
1511   {
1512     aCtx->arbFBO->glBindFramebuffer (GL_FRAMEBUFFER, OpenGl_FrameBuffer::NO_FRAMEBUFFER);
1513     aCtx->SetFrameBufferSRGB (false);
1514   }
1515   const Standard_Integer aViewport[4] = { 0, 0, aDrawSizeX, aDrawSizeY };
1516   aCtx->ResizeViewport (aViewport);
1517
1518   aCtx->SetColorMaskRGBA (NCollection_Vec4<bool> (true)); // force writes into all components, including alpha
1519   aCtx->core20fwd->glClearDepth (1.0);
1520   aCtx->core20fwd->glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
1521   aCtx->SetColorMask (true); // restore default alpha component write state
1522
1523   const bool toApplyGamma = aCtx->ToRenderSRGB() != aCtx->IsFrameBufferSRGB();
1524   if (aCtx->arbFBOBlit != NULL
1525   && !toApplyGamma
1526   &&  theReadFbo->NbSamples() != 0)
1527   {
1528     GLbitfield aCopyMask = 0;
1529     theReadFbo->BindReadBuffer (aCtx);
1530     if (theDrawFbo != NULL
1531      && theDrawFbo->IsValid())
1532     {
1533       theDrawFbo->BindDrawBuffer (aCtx);
1534       if (theDrawFbo->HasColor()
1535        && theReadFbo->HasColor())
1536       {
1537         aCopyMask |= GL_COLOR_BUFFER_BIT;
1538       }
1539       if (theDrawFbo->HasDepth()
1540        && theReadFbo->HasDepth())
1541       {
1542         aCopyMask |= GL_DEPTH_BUFFER_BIT;
1543       }
1544     }
1545     else
1546     {
1547       if (theReadFbo->HasColor())
1548       {
1549         aCopyMask |= GL_COLOR_BUFFER_BIT;
1550       }
1551       if (theReadFbo->HasDepth())
1552       {
1553         aCopyMask |= GL_DEPTH_BUFFER_BIT;
1554       }
1555       aCtx->arbFBO->glBindFramebuffer (GL_DRAW_FRAMEBUFFER, OpenGl_FrameBuffer::NO_FRAMEBUFFER);
1556       aCtx->SetFrameBufferSRGB (false);
1557     }
1558
1559     // we don't copy stencil buffer here... does it matter for performance?
1560     aCtx->arbFBOBlit->glBlitFramebuffer (0, 0, aReadSizeX, aReadSizeY,
1561                                          0, 0, aDrawSizeX, aDrawSizeY,
1562                                          aCopyMask, GL_NEAREST);
1563     const int anErr = ::glGetError();
1564     if (anErr != GL_NO_ERROR)
1565     {
1566       // glBlitFramebuffer() might fail in several cases:
1567       // - Both FBOs have MSAA and they are samples number does not match.
1568       //   OCCT checks that this does not happen,
1569       //   however some graphics drivers provide an option for overriding MSAA.
1570       //   In this case window MSAA might be non-zero (and application can not check it)
1571       //   and might not match MSAA of our offscreen FBOs.
1572       // - Pixel formats of FBOs do not match.
1573       //   This also might happen with window has pixel format,
1574       //   e.g. Mesa fails blitting RGBA8 -> RGB8 while other drivers support this conversion.
1575       TCollection_ExtendedString aMsg = TCollection_ExtendedString() + "FBO blitting has failed [Error #" + anErr + "]\n"
1576                                       + "  Please check your graphics driver settings or try updating driver.";
1577       if (theReadFbo->NbSamples() != 0)
1578       {
1579         myToDisableMSAA = true;
1580         aMsg += "\n  MSAA settings should not be overridden by driver!";
1581       }
1582       aCtx->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1583                          GL_DEBUG_TYPE_ERROR,
1584                          0,
1585                          GL_DEBUG_SEVERITY_HIGH,
1586                          aMsg);
1587     }
1588
1589     if (theDrawFbo != NULL
1590      && theDrawFbo->IsValid())
1591     {
1592       theDrawFbo->BindBuffer (aCtx);
1593     }
1594     else
1595     {
1596       aCtx->arbFBO->glBindFramebuffer (GL_FRAMEBUFFER, OpenGl_FrameBuffer::NO_FRAMEBUFFER);
1597       aCtx->SetFrameBufferSRGB (false);
1598     }
1599   }
1600   else
1601   {
1602     aCtx->core20fwd->glDepthFunc (GL_ALWAYS);
1603     aCtx->core20fwd->glDepthMask (GL_TRUE);
1604     aCtx->core20fwd->glEnable (GL_DEPTH_TEST);
1605   #if defined(GL_ES_VERSION_2_0)
1606     if (!aCtx->IsGlGreaterEqual (3, 0)
1607      && !aCtx->extFragDepth)
1608     {
1609       aCtx->core20fwd->glDisable (GL_DEPTH_TEST);
1610     }
1611   #endif
1612
1613     aCtx->BindTextures (Handle(OpenGl_TextureSet)(), Handle(OpenGl_ShaderProgram)());
1614
1615     const Graphic3d_TypeOfTextureFilter aFilter = (aDrawSizeX == aReadSizeX && aDrawSizeY == aReadSizeY) ? Graphic3d_TOTF_NEAREST : Graphic3d_TOTF_BILINEAR;
1616     const GLint aFilterGl = aFilter == Graphic3d_TOTF_NEAREST ? GL_NEAREST : GL_LINEAR;
1617
1618     OpenGl_VertexBuffer* aVerts = initBlitQuad (theToFlip);
1619     const Handle(OpenGl_ShaderManager)& aManager = aCtx->ShaderManager();
1620     if (aVerts->IsValid()
1621      && aManager->BindFboBlitProgram (theReadFbo != NULL ? theReadFbo->NbSamples() : 0, toApplyGamma))
1622     {
1623       aCtx->SetSampleAlphaToCoverage (false);
1624       theReadFbo->ColorTexture()->Bind (aCtx, Graphic3d_TextureUnit_0);
1625       if (theReadFbo->ColorTexture()->Sampler()->Parameters()->Filter() != aFilter)
1626       {
1627         theReadFbo->ColorTexture()->Sampler()->Parameters()->SetFilter (aFilter);
1628         aCtx->core20fwd->glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, aFilterGl);
1629         aCtx->core20fwd->glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, aFilterGl);
1630       }
1631
1632       theReadFbo->DepthStencilTexture()->Bind (aCtx, Graphic3d_TextureUnit_1);
1633       if (theReadFbo->DepthStencilTexture()->Sampler()->Parameters()->Filter() != aFilter)
1634       {
1635         theReadFbo->DepthStencilTexture()->Sampler()->Parameters()->SetFilter (aFilter);
1636         aCtx->core20fwd->glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, aFilterGl);
1637         aCtx->core20fwd->glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, aFilterGl);
1638       }
1639
1640       aVerts->BindVertexAttrib (aCtx, Graphic3d_TOA_POS);
1641
1642       aCtx->core20fwd->glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
1643
1644       aVerts->UnbindVertexAttrib (aCtx, Graphic3d_TOA_POS);
1645       theReadFbo->DepthStencilTexture()->Unbind (aCtx, Graphic3d_TextureUnit_1);
1646       theReadFbo->ColorTexture()       ->Unbind (aCtx, Graphic3d_TextureUnit_0);
1647       aCtx->BindProgram (NULL);
1648     }
1649     else
1650     {
1651       TCollection_ExtendedString aMsg = TCollection_ExtendedString()
1652         + "Error! FBO blitting has failed";
1653       aCtx->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1654                          GL_DEBUG_TYPE_ERROR,
1655                          0,
1656                          GL_DEBUG_SEVERITY_HIGH,
1657                          aMsg);
1658       myHasFboBlit = Standard_False;
1659       theReadFbo->Release (aCtx.operator->());
1660       return true;
1661     }
1662   }
1663   return true;
1664 }
1665
1666 // =======================================================================
1667 // function : drawStereoPair
1668 // purpose  :
1669 // =======================================================================
1670 void OpenGl_View::drawStereoPair (OpenGl_FrameBuffer* theDrawFbo)
1671 {
1672   const Handle(OpenGl_Context)& aCtx = myWorkspace->GetGlContext();
1673   bindDefaultFbo (theDrawFbo);
1674   OpenGl_FrameBuffer* aPair[2] =
1675   {
1676     myImmediateSceneFbos[0]->IsValid() ? myImmediateSceneFbos[0].operator->() : NULL,
1677     myImmediateSceneFbos[1]->IsValid() ? myImmediateSceneFbos[1].operator->() : NULL
1678   };
1679   if (aPair[0] == NULL
1680   ||  aPair[1] == NULL
1681   || !myTransientDrawToFront)
1682   {
1683     aPair[0] = myMainSceneFbos[0]->IsValid() ? myMainSceneFbos[0].operator->() : NULL;
1684     aPair[1] = myMainSceneFbos[1]->IsValid() ? myMainSceneFbos[1].operator->() : NULL;
1685   }
1686
1687   if (aPair[0] == NULL
1688    || aPair[1] == NULL)
1689   {
1690     return;
1691   }
1692
1693   if (aPair[0]->NbSamples() != 0)
1694   {
1695     // resolve MSAA buffers before drawing
1696     if (!myOpenGlFBO ->InitLazy (aCtx, aPair[0]->GetVPSizeX(), aPair[0]->GetVPSizeY(), myFboColorFormat, myFboDepthFormat, 0)
1697      || !myOpenGlFBO2->InitLazy (aCtx, aPair[0]->GetVPSizeX(), aPair[0]->GetVPSizeY(), myFboColorFormat, 0, 0))
1698     {
1699       aCtx->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1700                          GL_DEBUG_TYPE_ERROR,
1701                          0,
1702                          GL_DEBUG_SEVERITY_HIGH,
1703                          "Error! Unable to allocate FBO for blitting stereo pair");
1704       bindDefaultFbo (theDrawFbo);
1705       return;
1706     }
1707
1708     if (!blitBuffers (aPair[0], myOpenGlFBO .operator->(), Standard_False)
1709      || !blitBuffers (aPair[1], myOpenGlFBO2.operator->(), Standard_False))
1710     {
1711       bindDefaultFbo (theDrawFbo);
1712       return;
1713     }
1714
1715     aPair[0] = myOpenGlFBO .operator->();
1716     aPair[1] = myOpenGlFBO2.operator->();
1717     bindDefaultFbo (theDrawFbo);
1718   }
1719
1720   struct
1721   {
1722     Standard_Integer left;
1723     Standard_Integer top;
1724     Standard_Integer right;
1725     Standard_Integer bottom;
1726     Standard_Integer dx() { return right  - left; }
1727     Standard_Integer dy() { return bottom - top; }
1728   } aGeom;
1729
1730   myWindow->PlatformWindow()->Position (aGeom.left, aGeom.top, aGeom.right, aGeom.bottom);
1731
1732   Standard_Boolean toReverse = myRenderParams.ToReverseStereo;
1733   const Standard_Boolean isOddY = (aGeom.top + aGeom.dy()) % 2 == 1;
1734   const Standard_Boolean isOddX =  aGeom.left % 2 == 1;
1735   if (isOddY
1736    && (myRenderParams.StereoMode == Graphic3d_StereoMode_RowInterlaced
1737     || myRenderParams.StereoMode == Graphic3d_StereoMode_ChessBoard))
1738   {
1739     toReverse = !toReverse;
1740   }
1741   if (isOddX
1742    && (myRenderParams.StereoMode == Graphic3d_StereoMode_ColumnInterlaced
1743     || myRenderParams.StereoMode == Graphic3d_StereoMode_ChessBoard))
1744   {
1745     toReverse = !toReverse;
1746   }
1747
1748   if (toReverse)
1749   {
1750     std::swap (aPair[0], aPair[1]);
1751   }
1752
1753   aCtx->core20fwd->glDepthFunc (GL_ALWAYS);
1754   aCtx->core20fwd->glDepthMask (GL_TRUE);
1755   aCtx->core20fwd->glEnable (GL_DEPTH_TEST);
1756
1757   aCtx->BindTextures (Handle(OpenGl_TextureSet)(), Handle(OpenGl_ShaderProgram)());
1758   OpenGl_VertexBuffer* aVerts = initBlitQuad (myToFlipOutput);
1759
1760   const Handle(OpenGl_ShaderManager)& aManager = aCtx->ShaderManager();
1761   if (aVerts->IsValid()
1762    && aManager->BindStereoProgram (myRenderParams.StereoMode))
1763   {
1764     if (myRenderParams.StereoMode == Graphic3d_StereoMode_Anaglyph)
1765     {
1766       OpenGl_Mat4 aFilterL, aFilterR;
1767       aFilterL.SetDiagonal (Graphic3d_Vec4 (0.0f, 0.0f, 0.0f, 0.0f));
1768       aFilterR.SetDiagonal (Graphic3d_Vec4 (0.0f, 0.0f, 0.0f, 0.0f));
1769       switch (myRenderParams.AnaglyphFilter)
1770       {
1771         case Graphic3d_RenderingParams::Anaglyph_RedCyan_Simple:
1772         {
1773           aFilterL.SetRow (0, Graphic3d_Vec4 (1.0f, 0.0f, 0.0f, 0.0f));
1774           aFilterR.SetRow (1, Graphic3d_Vec4 (0.0f, 1.0f, 0.0f, 0.0f));
1775           aFilterR.SetRow (2, Graphic3d_Vec4 (0.0f, 0.0f, 1.0f, 0.0f));
1776           break;
1777         }
1778         case Graphic3d_RenderingParams::Anaglyph_RedCyan_Optimized:
1779         {
1780           aFilterL.SetRow (0, Graphic3d_Vec4 ( 0.4154f,      0.4710f,      0.16666667f, 0.0f));
1781           aFilterL.SetRow (1, Graphic3d_Vec4 (-0.0458f,     -0.0484f,     -0.0257f,     0.0f));
1782           aFilterL.SetRow (2, Graphic3d_Vec4 (-0.0547f,     -0.0615f,      0.0128f,     0.0f));
1783           aFilterL.SetRow (3, Graphic3d_Vec4 ( 0.0f,         0.0f,         0.0f,        0.0f));
1784           aFilterR.SetRow (0, Graphic3d_Vec4 (-0.01090909f, -0.03636364f, -0.00606061f, 0.0f));
1785           aFilterR.SetRow (1, Graphic3d_Vec4 ( 0.37560000f,  0.73333333f,  0.01111111f, 0.0f));
1786           aFilterR.SetRow (2, Graphic3d_Vec4 (-0.06510000f, -0.12870000f,  1.29710000f, 0.0f));
1787           aFilterR.SetRow (3, Graphic3d_Vec4 ( 0.0f,                0.0f,  0.0f,        0.0f));
1788           break;
1789         }
1790         case Graphic3d_RenderingParams::Anaglyph_YellowBlue_Simple:
1791         {
1792           aFilterL.SetRow (0, Graphic3d_Vec4 (1.0f, 0.0f, 0.0f, 0.0f));
1793           aFilterL.SetRow (1, Graphic3d_Vec4 (0.0f, 1.0f, 0.0f, 0.0f));
1794           aFilterR.SetRow (2, Graphic3d_Vec4 (0.0f, 0.0f, 1.0f, 0.0f));
1795           break;
1796         }
1797         case Graphic3d_RenderingParams::Anaglyph_YellowBlue_Optimized:
1798         {
1799           aFilterL.SetRow (0, Graphic3d_Vec4 ( 1.062f, -0.205f,  0.299f, 0.0f));
1800           aFilterL.SetRow (1, Graphic3d_Vec4 (-0.026f,  0.908f,  0.068f, 0.0f));
1801           aFilterL.SetRow (2, Graphic3d_Vec4 (-0.038f, -0.173f,  0.022f, 0.0f));
1802           aFilterL.SetRow (3, Graphic3d_Vec4 ( 0.0f,    0.0f,    0.0f,   0.0f));
1803           aFilterR.SetRow (0, Graphic3d_Vec4 (-0.016f, -0.123f, -0.017f, 0.0f));
1804           aFilterR.SetRow (1, Graphic3d_Vec4 ( 0.006f,  0.062f, -0.017f, 0.0f));
1805           aFilterR.SetRow (2, Graphic3d_Vec4 ( 0.094f,  0.185f,  0.911f, 0.0f));
1806           aFilterR.SetRow (3, Graphic3d_Vec4 ( 0.0f,    0.0f,    0.0f,   0.0f));
1807           break;
1808         }
1809         case Graphic3d_RenderingParams::Anaglyph_GreenMagenta_Simple:
1810         {
1811           aFilterR.SetRow (0, Graphic3d_Vec4 (1.0f, 0.0f, 0.0f, 0.0f));
1812           aFilterL.SetRow (1, Graphic3d_Vec4 (0.0f, 1.0f, 0.0f, 0.0f));
1813           aFilterR.SetRow (2, Graphic3d_Vec4 (0.0f, 0.0f, 1.0f, 0.0f));
1814           break;
1815         }
1816         case Graphic3d_RenderingParams::Anaglyph_UserDefined:
1817         {
1818           aFilterL = myRenderParams.AnaglyphLeft;
1819           aFilterR = myRenderParams.AnaglyphRight;
1820           break;
1821         }
1822       }
1823       aCtx->ActiveProgram()->SetUniform (aCtx, "uMultL", aFilterL);
1824       aCtx->ActiveProgram()->SetUniform (aCtx, "uMultR", aFilterR);
1825     }
1826
1827     aPair[0]->ColorTexture()->Bind (aCtx, Graphic3d_TextureUnit_0);
1828     aPair[1]->ColorTexture()->Bind (aCtx, Graphic3d_TextureUnit_1);
1829     aVerts->BindVertexAttrib (aCtx, 0);
1830
1831     aCtx->core20fwd->glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
1832
1833     aVerts->UnbindVertexAttrib (aCtx, 0);
1834     aPair[1]->ColorTexture()->Unbind (aCtx, Graphic3d_TextureUnit_1);
1835     aPair[0]->ColorTexture()->Unbind (aCtx, Graphic3d_TextureUnit_0);
1836   }
1837   else
1838   {
1839     TCollection_ExtendedString aMsg = TCollection_ExtendedString()
1840       + "Error! Anaglyph has failed";
1841     aCtx->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1842                        GL_DEBUG_TYPE_ERROR,
1843                        0,
1844                        GL_DEBUG_SEVERITY_HIGH,
1845                        aMsg);
1846   }
1847 }
1848
1849 // =======================================================================
1850 // function : copyBackToFront
1851 // purpose  :
1852 // =======================================================================
1853 bool OpenGl_View::copyBackToFront()
1854 {
1855   myIsImmediateDrawn = Standard_False;
1856 #if !defined(GL_ES_VERSION_2_0)
1857   const Handle(OpenGl_Context)& aCtx = myWorkspace->GetGlContext();
1858   if (aCtx->core11 == NULL)
1859   {
1860     return false;
1861   }
1862
1863   OpenGl_Mat4 aProjectMat;
1864   Graphic3d_TransformUtils::Ortho2D (aProjectMat,
1865                                      0.0f, static_cast<GLfloat> (myWindow->Width()),
1866                                      0.0f, static_cast<GLfloat> (myWindow->Height()));
1867
1868   aCtx->WorldViewState.Push();
1869   aCtx->ProjectionState.Push();
1870
1871   aCtx->WorldViewState.SetIdentity();
1872   aCtx->ProjectionState.SetCurrent (aProjectMat);
1873
1874   aCtx->ApplyProjectionMatrix();
1875   aCtx->ApplyWorldViewMatrix();
1876
1877   // synchronize FFP state before copying pixels
1878   aCtx->BindProgram (Handle(OpenGl_ShaderProgram)());
1879   aCtx->ShaderManager()->PushState (Handle(OpenGl_ShaderProgram)());
1880   aCtx->DisableFeatures();
1881
1882   switch (aCtx->DrawBuffer())
1883   {
1884     case GL_BACK_LEFT:
1885     {
1886       aCtx->SetReadBuffer (GL_BACK_LEFT);
1887       aCtx->SetDrawBuffer (GL_FRONT_LEFT);
1888       break;
1889     }
1890     case GL_BACK_RIGHT:
1891     {
1892       aCtx->SetReadBuffer (GL_BACK_RIGHT);
1893       aCtx->SetDrawBuffer (GL_FRONT_RIGHT);
1894       break;
1895     }
1896     default:
1897     {
1898       aCtx->SetReadBuffer (GL_BACK);
1899       aCtx->SetDrawBuffer (GL_FRONT);
1900       break;
1901     }
1902   }
1903
1904   aCtx->core11->glRasterPos2i (0, 0);
1905   aCtx->core11->glCopyPixels  (0, 0, myWindow->Width() + 1, myWindow->Height() + 1, GL_COLOR);
1906   //aCtx->core11->glCopyPixels  (0, 0, myWidth + 1, myHeight + 1, GL_DEPTH);
1907
1908   aCtx->EnableFeatures();
1909
1910   aCtx->WorldViewState.Pop();
1911   aCtx->ProjectionState.Pop();
1912   aCtx->ApplyProjectionMatrix();
1913
1914   // read/write from front buffer now
1915   aCtx->SetReadBuffer (aCtx->DrawBuffer());
1916   return true;
1917 #else
1918   return false;
1919 #endif
1920 }
1921
1922 // =======================================================================
1923 // function : checkOitCompatibility
1924 // purpose  :
1925 // =======================================================================
1926 Standard_Boolean OpenGl_View::checkOitCompatibility (const Handle(OpenGl_Context)& theGlContext,
1927                                                      const Standard_Boolean theMSAA)
1928 {
1929   // determine if OIT is supported by current OpenGl context
1930   Standard_Boolean& aToDisableOIT = theMSAA ? myToDisableMSAA : myToDisableOIT;
1931   if (aToDisableOIT)
1932   {
1933     return Standard_False;
1934   }
1935
1936   TCollection_ExtendedString aCompatibilityMsg;
1937   if (theGlContext->hasFloatBuffer     == OpenGl_FeatureNotAvailable
1938    && theGlContext->hasHalfFloatBuffer == OpenGl_FeatureNotAvailable)
1939   {
1940     aCompatibilityMsg += "OpenGL context does not support floating-point RGBA color buffer format.\n";
1941   }
1942   if (theMSAA && theGlContext->hasSampleVariables == OpenGl_FeatureNotAvailable)
1943   {
1944     aCompatibilityMsg += "Current version of GLSL does not support built-in sample variables.\n";
1945   }
1946   if (theGlContext->hasDrawBuffers == OpenGl_FeatureNotAvailable)
1947   {
1948     aCompatibilityMsg += "OpenGL context does not support multiple draw buffers.\n";
1949   }
1950   if (aCompatibilityMsg.IsEmpty())
1951   {
1952     return Standard_True;
1953   }
1954
1955   aCompatibilityMsg += "  Blended order-independent transparency will not be available.\n";
1956   theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1957                           GL_DEBUG_TYPE_ERROR,
1958                           0,
1959                           GL_DEBUG_SEVERITY_HIGH,
1960                           aCompatibilityMsg);
1961
1962   aToDisableOIT = Standard_True;
1963   return Standard_False;
1964 }
1965
1966 // =======================================================================
1967 // function : chooseOitColorConfiguration
1968 // purpose  :
1969 // =======================================================================
1970 bool OpenGl_View::chooseOitColorConfiguration (const Handle(OpenGl_Context)& theGlContext,
1971                                                const Standard_Integer theConfigIndex,
1972                                                OpenGl_ColorFormats& theFormats)
1973 {
1974   theFormats.Clear();
1975   switch (theConfigIndex)
1976   {
1977     case 0: // choose best applicable color format combination
1978     {
1979       theFormats.Append (theGlContext->hasHalfFloatBuffer != OpenGl_FeatureNotAvailable ? GL_RGBA16F : GL_RGBA32F);
1980       theFormats.Append (theGlContext->hasHalfFloatBuffer != OpenGl_FeatureNotAvailable ? GL_R16F    : GL_R32F);
1981       return true;
1982     }
1983     case 1: // choose non-optimal applicable color format combination
1984     {
1985       theFormats.Append (theGlContext->hasHalfFloatBuffer != OpenGl_FeatureNotAvailable ? GL_RGBA16F : GL_RGBA32F);
1986       theFormats.Append (theGlContext->hasHalfFloatBuffer != OpenGl_FeatureNotAvailable ? GL_RGBA16F : GL_RGBA32F);
1987       return true;
1988     }
1989   }
1990   return false; // color combination does not exist
1991 }
1992
1993 // =======================================================================
1994 // function : checkPBRAvailability
1995 // purpose  :
1996 // =======================================================================
1997 Standard_Boolean OpenGl_View::checkPBRAvailability() const
1998 {
1999   return myWorkspace->GetGlContext()->HasPBR()
2000       && !myPBREnvironment.IsNull();
2001 }
2002
2003 // =======================================================================
2004 // function : bakePBREnvironment
2005 // purpose  :
2006 // =======================================================================
2007 void OpenGl_View::bakePBREnvironment (const Handle(OpenGl_Context)& theCtx)
2008 {
2009   const Handle(OpenGl_TextureSet)& aTextureSet = myCubeMapParams->TextureSet (theCtx);
2010   if (!aTextureSet.IsNull()
2011    && !aTextureSet->IsEmpty())
2012   {
2013     myPBREnvironment->Bake (theCtx,
2014                             aTextureSet->First(),
2015                             myBackgroundCubeMap->ZIsInverted(),
2016                             myBackgroundCubeMap->IsTopDown(),
2017                             myRenderParams.PbrEnvBakingDiffNbSamples,
2018                             myRenderParams.PbrEnvBakingSpecNbSamples,
2019                             myRenderParams.PbrEnvBakingProbability);
2020   }
2021   else
2022   {
2023     myPBREnvironment->Clear (theCtx);
2024   }
2025 }
2026
2027 // =======================================================================
2028 // function : clearPBREnvironment
2029 // purpose  :
2030 // =======================================================================
2031 void OpenGl_View::clearPBREnvironment (const Handle(OpenGl_Context)& theCtx)
2032 {
2033   myPBREnvironment->Clear (theCtx);
2034 }
2035
2036 // =======================================================================
2037 // function : clearPBREnvironment
2038 // purpose  :
2039 // =======================================================================
2040 void OpenGl_View::processPBREnvRequest (const Handle(OpenGl_Context)& theCtx)
2041 {
2042   if (myPBREnvState == OpenGl_PBREnvState_CREATED)
2043   {
2044     switch (myPBREnvRequest)
2045     {
2046       case OpenGl_PBREnvRequest_NONE:  return;
2047       case OpenGl_PBREnvRequest_BAKE:  bakePBREnvironment  (theCtx); break;
2048       case OpenGl_PBREnvRequest_CLEAR: clearPBREnvironment (theCtx); break;
2049     }
2050   }
2051   myPBREnvRequest = OpenGl_PBREnvRequest_NONE;
2052 }