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