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