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