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