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