2bca09c991f71dfcd9d7ecc01116c5a6ff30452f
[occt.git] / src / OpenGl / OpenGl_View.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 <OpenGl_View.hxx>
17
18 #include <Aspect_RenderingContext.hxx>
19 #include <Aspect_Window.hxx>
20 #include <Aspect_XRSession.hxx>
21 #include <Graphic3d_AspectFillArea3d.hxx>
22 #include <Graphic3d_Texture2Dmanual.hxx>
23 #include <Graphic3d_TextureEnv.hxx>
24 #include <Graphic3d_Mat4d.hxx>
25 #include <Image_AlienPixMap.hxx>
26 #include <OpenGl_ArbFBO.hxx>
27 #include <OpenGl_BackgroundArray.hxx>
28 #include <OpenGl_Context.hxx>
29 #include <OpenGl_DepthPeeling.hxx>
30 #include <OpenGl_FrameBuffer.hxx>
31 #include <OpenGl_GlCore11.hxx>
32 #include <OpenGl_GraduatedTrihedron.hxx>
33 #include <OpenGl_GraphicDriver.hxx>
34 #include <OpenGl_ShaderManager.hxx>
35 #include <OpenGl_ShadowMap.hxx>
36 #include <OpenGl_Texture.hxx>
37 #include <OpenGl_Window.hxx>
38 #include <OpenGl_Workspace.hxx>
39 #include <OSD_Parallel.hxx>
40 #include <Standard_CLocaleSentry.hxx>
41
42 #include "../Graphic3d/Graphic3d_Structure.pxx"
43 #include "../Textures/Textures_EnvLUT.pxx"
44
45 namespace
46 {
47   //! Format Frame Buffer format for logging messages.
48   static TCollection_AsciiString printFboFormat (const Handle(OpenGl_FrameBuffer)& theFbo)
49   {
50     return TCollection_AsciiString() + theFbo->GetInitVPSizeX() + "x" + theFbo->GetInitVPSizeY() + "@" + theFbo->NbSamples();
51   }
52
53   //! Return TRUE if Frame Buffer initialized has failed with the same parameters.
54   static bool checkWasFailedFbo (const Handle(OpenGl_FrameBuffer)& theFboToCheck,
55                                  Standard_Integer theSizeX,
56                                  Standard_Integer theSizeY,
57                                  Standard_Integer theNbSamples)
58   {
59     return !theFboToCheck->IsValid()
60         &&  theFboToCheck->GetInitVPSizeX() == theSizeX
61         &&  theFboToCheck->GetInitVPSizeY() == theSizeY
62         &&  theFboToCheck->NbSamples()      == theNbSamples;
63   }
64
65   //! Return TRUE if Frame Buffer initialized has failed with the same parameters.
66   static bool checkWasFailedFbo (const Handle(OpenGl_FrameBuffer)& theFboToCheck,
67                                  const Handle(OpenGl_FrameBuffer)& theFboRef)
68   {
69     return checkWasFailedFbo (theFboToCheck, theFboRef->GetVPSizeX(), theFboRef->GetVPSizeY(), theFboRef->NbSamples());
70   }
71
72   //! Chooses compatible internal color format for OIT frame buffer.
73   static bool chooseOitColorConfiguration (const Handle(OpenGl_Context)& theGlContext,
74                                            const Standard_Integer theConfigIndex,
75                                            OpenGl_ColorFormats& theFormats)
76   {
77     theFormats.Clear();
78     switch (theConfigIndex)
79     {
80       case 0: // choose best applicable color format combination
81       {
82         theFormats.Append (theGlContext->hasHalfFloatBuffer != OpenGl_FeatureNotAvailable ? GL_RGBA16F : GL_RGBA32F);
83         theFormats.Append (theGlContext->hasHalfFloatBuffer != OpenGl_FeatureNotAvailable ? GL_R16F    : GL_R32F);
84         return true;
85       }
86       case 1: // choose non-optimal applicable color format combination
87       {
88         theFormats.Append (theGlContext->hasHalfFloatBuffer != OpenGl_FeatureNotAvailable ? GL_RGBA16F : GL_RGBA32F);
89         theFormats.Append (theGlContext->hasHalfFloatBuffer != OpenGl_FeatureNotAvailable ? GL_RGBA16F : GL_RGBA32F);
90         return true;
91       }
92     }
93     return false; // color combination does not exist
94   }
95 }
96
97 IMPLEMENT_STANDARD_RTTIEXT(OpenGl_View,Graphic3d_CView)
98
99 // =======================================================================
100 // function : Constructor
101 // purpose  :
102 // =======================================================================
103 OpenGl_View::OpenGl_View (const Handle(Graphic3d_StructureManager)& theMgr,
104                           const Handle(OpenGl_GraphicDriver)& theDriver,
105                           const Handle(OpenGl_Caps)& theCaps,
106                           OpenGl_StateCounter* theCounter)
107 : Graphic3d_CView  (theMgr),
108   myDriver         (theDriver.operator->()),
109   myCaps           (theCaps),
110   myWasRedrawnGL   (Standard_False),
111   myToShowGradTrihedron  (false),
112   myZLayers        (Structure_MAX_PRIORITY - Structure_MIN_PRIORITY + 1),
113   myStateCounter         (theCounter),
114   myCurrLightSourceState (theCounter->Increment()),
115   myLightsRevision       (0),
116   myLastLightSourceState (0, 0),
117   mySRgbState            (-1),
118   myFboColorFormat       (GL_SRGB8_ALPHA8), // note that GL_SRGB8 is not required to be renderable, unlike GL_RGB8, GL_RGBA8, GL_SRGB8_ALPHA8
119   myFboDepthFormat       (GL_DEPTH24_STENCIL8),
120   myToFlipOutput         (Standard_False),
121   //
122   myFrameCounter         (0),
123   myHasFboBlit           (Standard_True),
124   myToDisableOIT         (Standard_False),
125   myToDisableOITMSAA     (Standard_False),
126   myToDisableMSAA        (Standard_False),
127   myTransientDrawToFront (Standard_True),
128   myBackBufferRestored   (Standard_False),
129   myIsImmediateDrawn     (Standard_False),
130   myTextureParams   (new OpenGl_Aspects()),
131   myCubeMapParams   (new OpenGl_Aspects()),
132   myPBREnvState     (OpenGl_PBREnvState_NONEXISTENT),
133   myPBREnvRequest   (Standard_False),
134   // ray-tracing fields initialization
135   myRaytraceInitStatus     (OpenGl_RT_NONE),
136   myIsRaytraceDataValid    (Standard_False),
137   myIsRaytraceWarnTextures (Standard_False),
138   myRaytraceBVHBuilder (new BVH_BinnedBuilder<Standard_ShortReal, 3, BVH_Constants_NbBinsBest> (BVH_Constants_LeafNodeSizeAverage,
139                                                                                                 BVH_Constants_MaxTreeDepth,
140                                                                                                 Standard_False,
141                                                                                                 OSD_Parallel::NbLogicalProcessors() + 1)),
142   myRaytraceSceneRadius  (0.0f),
143   myRaytraceSceneEpsilon (1.0e-6f),
144   myToUpdateEnvironmentMap (Standard_False),
145   myRaytraceLayerListState (0),
146   myPrevCameraApertureRadius(0.f),
147   myPrevCameraFocalPlaneDist(0.f)
148 {
149   for (int i = 0; i < Graphic3d_TypeOfBackground_NB; ++i)
150   {
151     myBackgrounds[i] = new OpenGl_BackgroundArray(Graphic3d_TypeOfBackground(i));
152   }
153
154   myWorkspace = new OpenGl_Workspace (this, NULL);
155
156   Handle(Graphic3d_CLight) aLight = new Graphic3d_CLight (Graphic3d_TypeOfLightSource_Ambient);
157   aLight->SetColor (Quantity_NOC_WHITE);
158   myLights = new Graphic3d_LightSet();
159   myNoShadingLight = new Graphic3d_LightSet();
160   myNoShadingLight->Add (aLight);
161
162   myMainSceneFbos[0]         = new OpenGl_FrameBuffer();
163   myMainSceneFbos[1]         = new OpenGl_FrameBuffer();
164   myMainSceneFbosOit[0]      = new OpenGl_FrameBuffer();
165   myMainSceneFbosOit[1]      = new OpenGl_FrameBuffer();
166   myImmediateSceneFbos[0]    = new OpenGl_FrameBuffer();
167   myImmediateSceneFbos[1]    = new OpenGl_FrameBuffer();
168   myImmediateSceneFbosOit[0] = new OpenGl_FrameBuffer();
169   myImmediateSceneFbosOit[1] = new OpenGl_FrameBuffer();
170   myXrSceneFbo               = new OpenGl_FrameBuffer();
171   myOpenGlFBO                = new OpenGl_FrameBuffer();
172   myOpenGlFBO2               = new OpenGl_FrameBuffer();
173   myRaytraceFBO1[0]          = new OpenGl_FrameBuffer();
174   myRaytraceFBO1[1]          = new OpenGl_FrameBuffer();
175   myRaytraceFBO2[0]          = new OpenGl_FrameBuffer();
176   myRaytraceFBO2[1]          = new OpenGl_FrameBuffer();
177   myDepthPeelingFbos = new OpenGl_DepthPeeling();
178   myShadowMaps = new OpenGl_ShadowMapArray();
179 }
180
181 // =======================================================================
182 // function : Destructor
183 // purpose  :
184 // =======================================================================
185 OpenGl_View::~OpenGl_View()
186 {
187   ReleaseGlResources (NULL); // ensure ReleaseGlResources() was called within valid context
188   for (int i = 0; i < Graphic3d_TypeOfBackground_NB; ++i)
189   {
190     OpenGl_Element::Destroy(NULL, myBackgrounds[i]);
191   }
192
193   OpenGl_Element::Destroy (NULL, myTextureParams);
194   OpenGl_Element::Destroy (NULL, myCubeMapParams);
195 }
196
197 // =======================================================================
198 // function : releaseSrgbResources
199 // purpose  :
200 // =======================================================================
201 void OpenGl_View::releaseSrgbResources (const Handle(OpenGl_Context)& theCtx)
202 {
203   myRenderParams.RebuildRayTracingShaders = true;
204
205   if (!myTextureEnv.IsNull())
206   {
207     if (!theCtx.IsNull())
208     {
209       for (OpenGl_TextureSet::Iterator aTextureIter (myTextureEnv); aTextureIter.More(); aTextureIter.Next())
210       {
211         theCtx->DelayedRelease (aTextureIter.ChangeValue());
212         aTextureIter.ChangeValue().Nullify();
213       }
214     }
215     myTextureEnv.Nullify();
216   }
217
218   if (myTextureParams != NULL)
219   {
220     myTextureParams->Release (theCtx.get());
221   }
222
223   if (myCubeMapParams != NULL)
224   {
225     myCubeMapParams->Release (theCtx.get());
226   }
227
228   for (int i = 0; i < Graphic3d_TypeOfBackground_NB; ++i)
229   {
230     if (myBackgrounds[i] != NULL)
231     {
232       myBackgrounds[i]->Release (theCtx.get());
233     }
234   }
235
236   myMainSceneFbos[0]        ->Release (theCtx.get());
237   myMainSceneFbos[1]        ->Release (theCtx.get());
238   myMainSceneFbosOit[0]     ->Release (theCtx.get());
239   myMainSceneFbosOit[1]     ->Release (theCtx.get());
240   myImmediateSceneFbos[0]   ->Release (theCtx.get());
241   myImmediateSceneFbos[1]   ->Release (theCtx.get());
242   myImmediateSceneFbosOit[0]->Release (theCtx.get());
243   myImmediateSceneFbosOit[1]->Release (theCtx.get());
244   myXrSceneFbo              ->Release (theCtx.get());
245   myDepthPeelingFbos        ->Release (theCtx.get());
246   myOpenGlFBO               ->Release (theCtx.get());
247   myOpenGlFBO2              ->Release (theCtx.get());
248   myFullScreenQuad           .Release (theCtx.get());
249   myFullScreenQuadFlip       .Release (theCtx.get());
250   myShadowMaps->Release (theCtx.get());
251
252   // Technically we should also re-initialize all sRGB/RGB8 color textures.
253   // But for now consider this sRGB disabling/enabling to be done at application start-up
254   // and re-create dynamically only frame buffers.
255 }
256
257 // =======================================================================
258 // function : ReleaseGlResources
259 // purpose  :
260 // =======================================================================
261 void OpenGl_View::ReleaseGlResources (const Handle(OpenGl_Context)& theCtx)
262 {
263   myGraduatedTrihedron.Release (theCtx.get());
264   myFrameStatsPrs.Release (theCtx.get());
265
266   releaseSrgbResources (theCtx);
267
268   releaseRaytraceResources (theCtx);
269
270   if (!myPBREnvironment.IsNull())
271   {
272     myPBREnvironment->Release (theCtx.get());
273   }
274   ReleaseXR();
275 }
276
277 // =======================================================================
278 // function : Remove
279 // purpose  :
280 // =======================================================================
281 void OpenGl_View::Remove()
282 {
283   if (IsRemoved())
284   {
285     return;
286   }
287
288   myDriver->RemoveView (this);
289   myWindow.Nullify();
290
291   Graphic3d_CView::Remove();
292 }
293
294 // =======================================================================
295 // function : SetLocalOrigin
296 // purpose  :
297 // =======================================================================
298 void OpenGl_View::SetLocalOrigin (const gp_XYZ& theOrigin)
299 {
300   myLocalOrigin = theOrigin;
301   const Handle(OpenGl_Context)& aCtx = myWorkspace->GetGlContext();
302   if (!aCtx.IsNull())
303   {
304     aCtx->ShaderManager()->SetLocalOrigin (theOrigin);
305   }
306 }
307
308 // =======================================================================
309 // function : SetTextureEnv
310 // purpose  :
311 // =======================================================================
312 void OpenGl_View::SetTextureEnv (const Handle(Graphic3d_TextureEnv)& theTextureEnv)
313 {
314   Handle(OpenGl_Context) aCtx = myWorkspace->GetGlContext();
315   if (!aCtx.IsNull() && !myTextureEnv.IsNull())
316   {
317     for (OpenGl_TextureSet::Iterator aTextureIter (myTextureEnv); aTextureIter.More(); aTextureIter.Next())
318     {
319       aCtx->DelayedRelease (aTextureIter.ChangeValue());
320       aTextureIter.ChangeValue().Nullify();
321     }
322   }
323
324   myToUpdateEnvironmentMap = Standard_True;
325   myTextureEnvData = theTextureEnv;
326   myTextureEnv.Nullify();
327   initTextureEnv (aCtx);
328 }
329
330 // =======================================================================
331 // function : initTextureEnv
332 // purpose  :
333 // =======================================================================
334 void OpenGl_View::initTextureEnv (const Handle(OpenGl_Context)& theContext)
335 {
336   if (myTextureEnvData.IsNull()
337     ||  theContext.IsNull()
338     || !theContext->MakeCurrent())
339   {
340     return;
341   }
342
343   Handle(OpenGl_Texture) aTextureEnv = new OpenGl_Texture (myTextureEnvData->GetId(), myTextureEnvData->GetParams());
344   if (Handle(Image_PixMap) anImage = myTextureEnvData->GetImage (theContext->SupportedTextureFormats()))
345   {
346     aTextureEnv->Init (theContext, *anImage, myTextureEnvData->Type(), true);
347   }
348   myTextureEnv = new OpenGl_TextureSet (aTextureEnv);
349   myTextureEnv->ChangeTextureSetBits() = Graphic3d_TextureSetBits_BaseColor;
350 }
351
352 // =======================================================================
353 // function : SetImmediateModeDrawToFront
354 // purpose  :
355 // =======================================================================
356 Standard_Boolean OpenGl_View::SetImmediateModeDrawToFront (const Standard_Boolean theDrawToFrontBuffer)
357 {
358   const Standard_Boolean aPrevMode = myTransientDrawToFront;
359   myTransientDrawToFront = theDrawToFrontBuffer;
360   return aPrevMode;
361 }
362
363 // =======================================================================
364 // function : Window
365 // purpose  :
366 // =======================================================================
367 Handle(Aspect_Window) OpenGl_View::Window() const
368 {
369   return myWindow->PlatformWindow();
370 }
371
372 // =======================================================================
373 // function : SetWindow
374 // purpose  :
375 // =======================================================================
376 void OpenGl_View::SetWindow (const Handle(Aspect_Window)& theWindow,
377                              const Aspect_RenderingContext theContext)
378 {
379   myWindow = myDriver->CreateRenderWindow (theWindow, theContext);
380   Standard_ASSERT_RAISE (!myWindow.IsNull(),
381                          "OpenGl_View::SetWindow, "
382                          "Failed to create OpenGl window.");
383
384   myWorkspace = new OpenGl_Workspace (this, myWindow);
385   myWorldViewProjState.Reset();
386   myToUpdateEnvironmentMap = Standard_True;
387   myHasFboBlit = Standard_True;
388   Invalidate();
389
390   // Environment texture resource does not support lazy initialization.
391   initTextureEnv (myWorkspace->GetGlContext());
392 }
393
394 // =======================================================================
395 // function : Resized
396 // purpose  :
397 // =======================================================================
398 void OpenGl_View::Resized()
399 {
400   if (myWindow.IsNull())
401     return;
402
403   myWindow->Resize();
404 }
405
406 // =======================================================================
407 // function : SetMinMaxValuesCallback
408 // purpose  :
409 // =======================================================================
410 static void SetMinMaxValuesCallback (Graphic3d_CView* theView)
411 {
412   OpenGl_View* aView = dynamic_cast<OpenGl_View*>(theView);
413   if (aView == NULL)
414     return;
415
416   Bnd_Box aBox = theView->MinMaxValues();
417   if (!aBox.IsVoid())
418   {
419     gp_Pnt aMin = aBox.CornerMin();
420     gp_Pnt aMax = aBox.CornerMax();
421
422     Graphic3d_Vec3 aMinVec ((Standard_ShortReal )aMin.X(), (Standard_ShortReal )aMin.Y(), (Standard_ShortReal )aMin.Z());
423     Graphic3d_Vec3 aMaxVec ((Standard_ShortReal )aMax.X(), (Standard_ShortReal )aMax.Y(), (Standard_ShortReal )aMax.Z());
424     aView->GraduatedTrihedronMinMaxValues (aMinVec, aMaxVec);
425   }
426 }
427
428 // =======================================================================
429 // function : GraduatedTrihedronDisplay
430 // purpose  :
431 // =======================================================================
432 void OpenGl_View::GraduatedTrihedronDisplay (const Graphic3d_GraduatedTrihedron& theTrihedronData)
433 {
434   myGTrihedronData = theTrihedronData;
435   myGTrihedronData.SetCubicAxesCallback (SetMinMaxValuesCallback);
436   myGraduatedTrihedron.SetValues (myGTrihedronData);
437   myToShowGradTrihedron = true;
438 }
439
440 // =======================================================================
441 // function : GraduatedTrihedronErase
442 // purpose  :
443 // =======================================================================
444 void OpenGl_View::GraduatedTrihedronErase()
445 {
446   myGraduatedTrihedron.Release (myWorkspace->GetGlContext().operator->());
447   myToShowGradTrihedron = false;
448 }
449
450 // =======================================================================
451 // function : GraduatedTrihedronMinMaxValues
452 // purpose  :
453 // =======================================================================
454 void OpenGl_View::GraduatedTrihedronMinMaxValues (const Graphic3d_Vec3 theMin, const Graphic3d_Vec3 theMax)
455 {
456   myGraduatedTrihedron.SetMinMax (theMin, theMax);
457 }
458
459 // =======================================================================
460 // function : BufferDump
461 // purpose  :
462 // =======================================================================
463 Standard_Boolean OpenGl_View::BufferDump (Image_PixMap& theImage, const Graphic3d_BufferType& theBufferType)
464 {
465   if (theBufferType != Graphic3d_BT_RGB_RayTraceHdrLeft)
466   {
467     return myWorkspace->BufferDump(myFBO, theImage, theBufferType);
468   }
469
470   if (!myRaytraceParameters.AdaptiveScreenSampling)
471   {
472     return myWorkspace->BufferDump(myAccumFrames % 2 ? myRaytraceFBO2[0] : myRaytraceFBO1[0], theImage, theBufferType);
473   }
474
475 #if defined(GL_ES_VERSION_2_0)
476   return false;
477 #else
478   if (theImage.Format() != Image_Format_RGBF)
479   {
480     return false;
481   }
482
483   const GLuint aW = myRaytraceOutputTexture[0]->SizeX();
484   const GLuint aH = myRaytraceOutputTexture[0]->SizeY();
485   if (aW / 3 != theImage.SizeX() || aH / 2 != theImage.SizeY())
486   {
487     return false;
488   }
489
490   std::vector<GLfloat> aValues;
491   try
492   {
493     aValues.resize (aW * aH);
494   }
495   catch (const std::bad_alloc&)
496   {
497     return false;
498   }
499
500   glBindTexture (GL_TEXTURE_RECTANGLE, myRaytraceOutputTexture[0]->TextureId());
501   glGetTexImage (GL_TEXTURE_RECTANGLE, 0, OpenGl_TextureFormat::Create<GLfloat, 1>().Format(), GL_FLOAT, &aValues[0]);
502   glBindTexture (GL_TEXTURE_RECTANGLE, 0);
503   for (unsigned int aRow = 0; aRow < aH; aRow += 2)
504   {
505     for (unsigned int aCol = 0; aCol < aW; aCol += 3)
506     {
507       float* anImageValue = theImage.ChangeValue<float[3]> ((aH - aRow) / 2 - 1, aCol / 3);
508       float aInvNbSamples = 1.f / aValues[aRow * aW + aCol + aW];
509       anImageValue[0] = aValues[aRow * aW + aCol] * aInvNbSamples;
510       anImageValue[1] = aValues[aRow * aW + aCol + 1] * aInvNbSamples;
511       anImageValue[2] = aValues[aRow * aW + aCol + 1 + aW] * aInvNbSamples;
512     }
513   }
514
515   return true;
516 #endif
517 }
518
519 // =======================================================================
520 // function : GradientBackground
521 // purpose  :
522 // =======================================================================
523 Aspect_GradientBackground OpenGl_View::GradientBackground() const
524 {
525   Quantity_Color aColor1, aColor2;
526   aColor1.SetValues (myBackgrounds[Graphic3d_TOB_GRADIENT]->GradientColor (0).r(),
527                      myBackgrounds[Graphic3d_TOB_GRADIENT]->GradientColor (0).g(),
528                      myBackgrounds[Graphic3d_TOB_GRADIENT]->GradientColor (0).b(), Quantity_TOC_RGB);
529   aColor2.SetValues (myBackgrounds[Graphic3d_TOB_GRADIENT]->GradientColor (1).r(),
530                      myBackgrounds[Graphic3d_TOB_GRADIENT]->GradientColor (1).g(),
531                      myBackgrounds[Graphic3d_TOB_GRADIENT]->GradientColor (1).b(), Quantity_TOC_RGB);
532   return Aspect_GradientBackground (aColor1, aColor2, myBackgrounds[Graphic3d_TOB_GRADIENT]->GradientFillMethod());
533 }
534
535 // =======================================================================
536 // function : SetGradientBackground
537 // purpose  :
538 // =======================================================================
539 void OpenGl_View::SetGradientBackground (const Aspect_GradientBackground& theBackground)
540 {
541   Quantity_Color aColor1, aColor2;
542   theBackground.Colors (aColor1, aColor2);
543   myBackgrounds[Graphic3d_TOB_GRADIENT]->SetGradientParameters (aColor1, aColor2, theBackground.BgGradientFillMethod());
544
545   myBackgroundType = Graphic3d_TOB_GRADIENT;
546 }
547
548 // =======================================================================
549 // function : SetBackgroundImage
550 // purpose  :
551 // =======================================================================
552 void OpenGl_View::SetBackgroundImage (const Handle(Graphic3d_TextureMap)& theTextureMap,
553                                       Standard_Boolean theToUpdatePBREnv)
554 {
555   Handle(Graphic3d_TextureMap) aNewMap = theTextureMap;
556   if (theTextureMap.IsNull()
557   || !theTextureMap->IsDone())
558   {
559     if (!theTextureMap.IsNull())
560     {
561       Message::SendFail ("Error: unable to set image background");
562     }
563     aNewMap.Nullify();
564   }
565
566   Handle(Graphic3d_CubeMap) aCubeMap = Handle(Graphic3d_CubeMap)::DownCast (aNewMap);
567   if (theToUpdatePBREnv)
568   {
569     // update PBR environment
570     const TCollection_AsciiString anIdOld = !myCubeMapIBL.IsNull()
571                                            ? myCubeMapIBL->GetId()
572                                            : TCollection_AsciiString();
573     const TCollection_AsciiString anIdNew = !aCubeMap.IsNull()
574                                            ? aCubeMap->GetId()
575                                            : TCollection_AsciiString();
576     if (anIdNew != anIdOld)
577     {
578       myPBREnvRequest = true;
579     }
580     myCubeMapIBL = aCubeMap;
581   }
582
583   if (aNewMap.IsNull())
584   {
585     if (myBackgroundType == Graphic3d_TOB_TEXTURE
586      || myBackgroundType == Graphic3d_TOB_CUBEMAP)
587     {
588       myBackgroundType = Graphic3d_TOB_NONE;
589     }
590     return;
591   }
592
593   Handle(Graphic3d_AspectFillArea3d) anAspect = new Graphic3d_AspectFillArea3d();
594   Handle(Graphic3d_TextureSet) aTextureSet = new Graphic3d_TextureSet (aNewMap);
595   anAspect->SetInteriorStyle (Aspect_IS_SOLID);
596   anAspect->SetFaceCulling (Graphic3d_TypeOfBackfacingModel_DoubleSided);
597   anAspect->SetShadingModel (Graphic3d_TypeOfShadingModel_Unlit);
598   anAspect->SetTextureSet (aTextureSet);
599   anAspect->SetTextureMapOn (true);
600
601   if (Handle(Graphic3d_Texture2D) aTextureMap = Handle(Graphic3d_Texture2D)::DownCast (aNewMap))
602   {
603     myTextureParams->SetAspect (anAspect);
604     myBackgroundType  = Graphic3d_TOB_TEXTURE;
605     myBackgroundImage = aTextureMap;
606     return;
607   }
608
609   if (!aCubeMap.IsNull())
610   {
611     aCubeMap->SetMipmapsGeneration (Standard_True);
612     if (const Handle(OpenGl_Context)& aCtx = myWorkspace->GetGlContext())
613     {
614       anAspect->SetShaderProgram (aCtx->ShaderManager()->GetBgCubeMapProgram());
615     }
616
617     myCubeMapParams->SetAspect (anAspect);
618
619     const OpenGl_Aspects* anAspectsBackup = myWorkspace->SetAspects (myCubeMapParams);
620     myWorkspace->ApplyAspects();
621     myWorkspace->SetAspects (anAspectsBackup);
622     myWorkspace->ApplyAspects();
623
624     myBackgroundType = Graphic3d_TOB_CUBEMAP;
625     myCubeMapBackground = aCubeMap;
626     return;
627   }
628
629   throw Standard_ProgramError ("OpenGl_View::SetBackgroundImage() - invalid texture map set for background");
630 }
631
632 // =======================================================================
633 // function : SetImageBasedLighting
634 // purpose  :
635 // =======================================================================
636 void OpenGl_View::SetImageBasedLighting (Standard_Boolean theToEnableIBL)
637 {
638   if (!theToEnableIBL
639     || myBackgroundType != Graphic3d_TOB_CUBEMAP)
640   {
641     if (!myCubeMapIBL.IsNull())
642     {
643       myPBREnvRequest = true;
644       myCubeMapIBL.Nullify();
645     }
646     return;
647   }
648
649   const TCollection_AsciiString anIdOld = !myCubeMapIBL.IsNull()
650                                          ? myCubeMapIBL->GetId()
651                                          : TCollection_AsciiString();
652   const TCollection_AsciiString anIdNew = !myCubeMapBackground.IsNull()
653                                          ? myCubeMapBackground->GetId()
654                                          : TCollection_AsciiString();
655   if (anIdNew != anIdOld)
656   {
657     myPBREnvRequest = true;
658   }
659   myCubeMapIBL = myCubeMapBackground;
660 }
661
662 // =======================================================================
663 // function : BackgroundImageStyle
664 // purpose  :
665 // =======================================================================
666 Aspect_FillMethod OpenGl_View::BackgroundImageStyle() const
667 {
668   return myBackgrounds[Graphic3d_TOB_TEXTURE]->TextureFillMethod();
669 }
670
671 // =======================================================================
672 // function : SetBackgroundImageStyle
673 // purpose  :
674 // =======================================================================
675 void OpenGl_View::SetBackgroundImageStyle (const Aspect_FillMethod theFillStyle)
676 {
677   myBackgrounds[Graphic3d_TOB_TEXTURE]->SetTextureFillMethod (theFillStyle);
678 }
679
680 // =======================================================================
681 // function : SpecIBLMapLevels
682 // purpose  :
683 // =======================================================================
684 unsigned int OpenGl_View::SpecIBLMapLevels() const
685 {
686   return myPBREnvironment.IsNull() ? 0 : myPBREnvironment->SpecMapLevelsNumber();
687 }
688
689 //=======================================================================
690 //function : InsertLayerBefore
691 //purpose  :
692 //=======================================================================
693 void OpenGl_View::InsertLayerBefore (const Graphic3d_ZLayerId theLayerId,
694   const Graphic3d_ZLayerSettings& theSettings,
695   const Graphic3d_ZLayerId theLayerAfter)
696 {
697   myZLayers.InsertLayerBefore (theLayerId, theSettings, theLayerAfter);
698 }
699
700 //=======================================================================
701 //function : InsertLayerAfter
702 //purpose  :
703 //=======================================================================
704 void OpenGl_View::InsertLayerAfter (const Graphic3d_ZLayerId theLayerId,
705   const Graphic3d_ZLayerSettings& theSettings,
706   const Graphic3d_ZLayerId theLayerBefore)
707 {
708   myZLayers.InsertLayerAfter (theLayerId, theSettings, theLayerBefore);
709 }
710
711 //=======================================================================
712 //function : RemoveZLayer
713 //purpose  :
714 //=======================================================================
715 void OpenGl_View::RemoveZLayer (const Graphic3d_ZLayerId theLayerId)
716 {
717   myZLayers.RemoveLayer (theLayerId);
718 }
719
720 //=======================================================================
721 //function : SetZLayerSettings
722 //purpose  :
723 //=======================================================================
724 void OpenGl_View::SetZLayerSettings (const Graphic3d_ZLayerId        theLayerId,
725                                      const Graphic3d_ZLayerSettings& theSettings)
726 {
727   myZLayers.SetLayerSettings (theLayerId, theSettings);
728 }
729
730 //=======================================================================
731 //function : ZLayerMax
732 //purpose  :
733 //=======================================================================
734 Standard_Integer OpenGl_View::ZLayerMax() const
735 {
736   Standard_Integer aLayerMax = Graphic3d_ZLayerId_Default;
737   for (NCollection_List<Handle(Graphic3d_Layer)>::Iterator aLayerIter (myZLayers.Layers()); aLayerIter.More(); aLayerIter.Next())
738   {
739     aLayerMax = Max (aLayerMax, aLayerIter.Value()->LayerId());
740   }
741   return aLayerMax;
742 }
743
744 //=======================================================================
745 //function : Layers
746 //purpose  :
747 //=======================================================================
748 const NCollection_List<Handle(Graphic3d_Layer)>& OpenGl_View::Layers() const
749 {
750   return myZLayers.Layers();
751 }
752
753 //=======================================================================
754 //function : Layer
755 //purpose  :
756 //=======================================================================
757 Handle(Graphic3d_Layer) OpenGl_View::Layer (const Graphic3d_ZLayerId theLayerId) const
758 {
759   Handle(Graphic3d_Layer) aLayer;
760   if (theLayerId != Graphic3d_ZLayerId_UNKNOWN)
761   {
762     myZLayers.LayerIDs().Find (theLayerId, aLayer);
763   }
764   return aLayer;
765 }
766
767 //=======================================================================
768 //function : MinMaxValues
769 //purpose  :
770 //=======================================================================
771 Bnd_Box OpenGl_View::MinMaxValues (const Standard_Boolean theToIncludeAuxiliary) const
772 {
773   if (!IsDefined())
774   {
775     return Bnd_Box();
776   }
777
778   Bnd_Box aBox = base_type::MinMaxValues (theToIncludeAuxiliary);
779
780   return aBox;
781 }
782
783 //=======================================================================
784 //function : FBO
785 //purpose  :
786 //=======================================================================
787 Handle(Standard_Transient) OpenGl_View::FBO() const
788 {
789   return Handle(Standard_Transient)(myFBO);
790 }
791
792 //=======================================================================
793 //function : SetFBO
794 //purpose  :
795 //=======================================================================
796 void OpenGl_View::SetFBO (const Handle(Standard_Transient)& theFbo)
797 {
798   myFBO = Handle(OpenGl_FrameBuffer)::DownCast (theFbo);
799 }
800
801 //=======================================================================
802 //function : FBOCreate
803 //purpose  :
804 //=======================================================================
805 Handle(Standard_Transient) OpenGl_View::FBOCreate (const Standard_Integer theWidth,
806                                                    const Standard_Integer theHeight)
807 {
808   return myWorkspace->FBOCreate (theWidth, theHeight);
809 }
810
811 //=======================================================================
812 //function : FBORelease
813 //purpose  :
814 //=======================================================================
815 void OpenGl_View::FBORelease (Handle(Standard_Transient)& theFbo)
816 {
817   Handle(OpenGl_FrameBuffer) aFrameBuffer = Handle(OpenGl_FrameBuffer)::DownCast (theFbo);
818   if (aFrameBuffer.IsNull())
819   {
820     return;
821   }
822
823   myWorkspace->FBORelease (aFrameBuffer);
824   theFbo.Nullify();
825 }
826
827 //=======================================================================
828 //function : FBOGetDimensions
829 //purpose  :
830 //=======================================================================
831 void OpenGl_View::FBOGetDimensions (const Handle(Standard_Transient)& theFbo,
832                                     Standard_Integer& theWidth,
833                                     Standard_Integer& theHeight,
834                                     Standard_Integer& theWidthMax,
835                                     Standard_Integer& theHeightMax)
836 {
837   const Handle(OpenGl_FrameBuffer) aFrameBuffer = Handle(OpenGl_FrameBuffer)::DownCast (theFbo);
838   if (aFrameBuffer.IsNull())
839   {
840     return;
841   }
842
843   theWidth     = aFrameBuffer->GetVPSizeX(); // current viewport size
844   theHeight    = aFrameBuffer->GetVPSizeY();
845   theWidthMax  = aFrameBuffer->GetSizeX(); // texture size
846   theHeightMax = aFrameBuffer->GetSizeY();
847 }
848
849 //=======================================================================
850 //function : FBOChangeViewport
851 //purpose  :
852 //=======================================================================
853 void OpenGl_View::FBOChangeViewport (const Handle(Standard_Transient)& theFbo,
854                                      const Standard_Integer theWidth,
855                                      const Standard_Integer theHeight)
856 {
857   const Handle(OpenGl_FrameBuffer) aFrameBuffer = Handle(OpenGl_FrameBuffer)::DownCast (theFbo);
858   if (aFrameBuffer.IsNull())
859   {
860     return;
861   }
862
863   aFrameBuffer->ChangeViewport (theWidth, theHeight);
864 }
865
866 //=======================================================================
867 //function : displayStructure
868 //purpose  :
869 //=======================================================================
870 void OpenGl_View::displayStructure (const Handle(Graphic3d_CStructure)& theStructure,
871                                     const Standard_Integer              thePriority)
872 {
873   const OpenGl_Structure*  aStruct = static_cast<const OpenGl_Structure*> (theStructure.get());
874   const Graphic3d_ZLayerId aZLayer = aStruct->ZLayer();
875   myZLayers.AddStructure (aStruct, aZLayer, thePriority);
876 }
877
878 //=======================================================================
879 //function : eraseStructure
880 //purpose  :
881 //=======================================================================
882 void OpenGl_View::eraseStructure (const Handle(Graphic3d_CStructure)& theStructure)
883 {
884   const OpenGl_Structure* aStruct = static_cast<const OpenGl_Structure*> (theStructure.get());
885   myZLayers.RemoveStructure (aStruct);
886 }
887
888 //=======================================================================
889 //function : changeZLayer
890 //purpose  :
891 //=======================================================================
892 void OpenGl_View::changeZLayer (const Handle(Graphic3d_CStructure)& theStructure,
893                                 const Graphic3d_ZLayerId theNewLayerId)
894 {
895   const Graphic3d_ZLayerId anOldLayer = theStructure->ZLayer();
896   const OpenGl_Structure* aStruct = static_cast<const OpenGl_Structure*> (theStructure.get());
897   myZLayers.ChangeLayer (aStruct, anOldLayer, theNewLayerId);
898   Update (anOldLayer);
899   Update (theNewLayerId);
900 }
901
902 //=======================================================================
903 //function : changePriority
904 //purpose  :
905 //=======================================================================
906 void OpenGl_View::changePriority (const Handle(Graphic3d_CStructure)& theStructure,
907                                   const Standard_Integer theNewPriority)
908 {
909   const Graphic3d_ZLayerId aLayerId = theStructure->ZLayer();
910   const OpenGl_Structure* aStruct = static_cast<const OpenGl_Structure*> (theStructure.get());
911   myZLayers.ChangePriority (aStruct, aLayerId, theNewPriority);
912 }
913
914 //=======================================================================
915 //function : DiagnosticInformation
916 //purpose  :
917 //=======================================================================
918 void OpenGl_View::DiagnosticInformation (TColStd_IndexedDataMapOfStringString& theDict,
919                                          Graphic3d_DiagnosticInfo theFlags) const
920 {
921   base_type::DiagnosticInformation (theDict, theFlags);
922   Handle(OpenGl_Context) aCtx = myWorkspace->GetGlContext();
923   if (!myWorkspace->Activate()
924    || aCtx.IsNull())
925   {
926     return;
927   }
928
929   aCtx->DiagnosticInformation (theDict, theFlags);
930   if ((theFlags & Graphic3d_DiagnosticInfo_FrameBuffer) != 0)
931   {
932     TCollection_AsciiString aResRatio (myRenderParams.ResolutionRatio());
933     theDict.ChangeFromIndex (theDict.Add ("ResolutionRatio", aResRatio)) = aResRatio;
934   }
935 }
936
937 //=======================================================================
938 //function : StatisticInformation
939 //purpose  :
940 //=======================================================================
941 void OpenGl_View::StatisticInformation (TColStd_IndexedDataMapOfStringString& theDict) const
942 {
943   if (const Handle(OpenGl_Context)& aCtx = myWorkspace->GetGlContext())
944   {
945     const Handle(OpenGl_FrameStats)& aStats = aCtx->FrameStats();
946     const Graphic3d_RenderingParams& aRendParams = myWorkspace->View()->RenderingParams();
947     aStats->FormatStats (theDict, aRendParams.CollectedStats);
948   }
949 }
950
951 //=======================================================================
952 //function : StatisticInformation
953 //purpose  :
954 //=======================================================================
955 TCollection_AsciiString OpenGl_View::StatisticInformation() const
956 {
957   if (const Handle(OpenGl_Context)& aCtx = myWorkspace->GetGlContext())
958   {
959     const Handle(OpenGl_FrameStats)& aStats = aCtx->FrameStats();
960     const Graphic3d_RenderingParams& aRendParams = myWorkspace->View()->RenderingParams();
961     return aStats->FormatStats (aRendParams.CollectedStats);
962   }
963   return TCollection_AsciiString();
964 }
965
966 //=======================================================================
967 //function : drawBackground
968 //purpose  :
969 //=======================================================================
970 void OpenGl_View::drawBackground (const Handle(OpenGl_Workspace)& theWorkspace,
971                                   Graphic3d_Camera::Projection theProjection)
972 {
973   const Handle(OpenGl_Context)& aCtx = theWorkspace->GetGlContext();
974   const bool wasUsedZBuffer = theWorkspace->SetUseZBuffer (false);
975   if (wasUsedZBuffer)
976   {
977     aCtx->core11fwd->glDisable (GL_DEPTH_TEST);
978   }
979
980 #ifdef GL_DEPTH_CLAMP
981   const bool wasDepthClamped = aCtx->arbDepthClamp && glIsEnabled (GL_DEPTH_CLAMP);
982   if (aCtx->arbDepthClamp && !wasDepthClamped)
983   {
984     // make sure background is always drawn (workaround skybox rendering on some hardware)
985     aCtx->core11fwd->glEnable (GL_DEPTH_CLAMP);
986   }
987 #endif
988
989   if (myBackgroundType == Graphic3d_TOB_CUBEMAP)
990   {
991     myCubeMapParams->Aspect()->ShaderProgram()->PushVariableInt ("uZCoeff", myCubeMapBackground->ZIsInverted() ? -1 : 1);
992     myCubeMapParams->Aspect()->ShaderProgram()->PushVariableInt ("uYCoeff", myCubeMapBackground->IsTopDown() ? 1 : -1);
993     const OpenGl_Aspects* anOldAspectFace = theWorkspace->SetAspects (myCubeMapParams);
994
995     myBackgrounds[Graphic3d_TOB_CUBEMAP]->Render (theWorkspace, theProjection);
996
997     theWorkspace->SetAspects (anOldAspectFace);
998   }
999   else if (myBackgroundType == Graphic3d_TOB_GRADIENT
1000         || myBackgroundType == Graphic3d_TOB_TEXTURE)
1001   {
1002     // Drawing background gradient if:
1003     // - gradient fill type is not Aspect_GradientFillMethod_None and
1004     // - either background texture is no specified or it is drawn in Aspect_FM_CENTERED mode
1005     if (myBackgrounds[Graphic3d_TOB_GRADIENT]->IsDefined()
1006       && (!myTextureParams->Aspect()->ToMapTexture()
1007         || myBackgrounds[Graphic3d_TOB_TEXTURE]->TextureFillMethod() == Aspect_FM_CENTERED
1008         || myBackgrounds[Graphic3d_TOB_TEXTURE]->TextureFillMethod() == Aspect_FM_NONE))
1009     {
1010       myBackgrounds[Graphic3d_TOB_GRADIENT]->Render(theWorkspace, theProjection);
1011     }
1012
1013     // Drawing background image if it is defined
1014     // (texture is defined and fill type is not Aspect_FM_NONE)
1015     if (myBackgrounds[Graphic3d_TOB_TEXTURE]->IsDefined()
1016       && myTextureParams->Aspect()->ToMapTexture())
1017     {
1018       aCtx->core11fwd->glDisable (GL_BLEND);
1019
1020       const OpenGl_Aspects* anOldAspectFace = theWorkspace->SetAspects (myTextureParams);
1021       myBackgrounds[Graphic3d_TOB_TEXTURE]->Render (theWorkspace, theProjection);
1022       theWorkspace->SetAspects (anOldAspectFace);
1023     }
1024   }
1025
1026   if (wasUsedZBuffer)
1027   {
1028     theWorkspace->SetUseZBuffer (Standard_True);
1029     aCtx->core11fwd->glEnable (GL_DEPTH_TEST);
1030   }
1031 #ifdef GL_DEPTH_CLAMP
1032   if (aCtx->arbDepthClamp && !wasDepthClamped)
1033   {
1034     aCtx->core11fwd->glDisable (GL_DEPTH_CLAMP);
1035   }
1036 #endif
1037 }
1038
1039 //=======================================================================
1040 //function : prepareFrameBuffers
1041 //purpose  :
1042 //=======================================================================
1043 bool OpenGl_View::prepareFrameBuffers (Graphic3d_Camera::Projection& theProj)
1044 {
1045   theProj = myCamera->ProjectionType();
1046   const Handle(OpenGl_Context)& aCtx = myWorkspace->GetGlContext();
1047
1048   Standard_Integer aSizeX = 0, aSizeY = 0;
1049   OpenGl_FrameBuffer* aFrameBuffer = myFBO.get();
1050   if (aFrameBuffer != NULL)
1051   {
1052     aSizeX = aFrameBuffer->GetVPSizeX();
1053     aSizeY = aFrameBuffer->GetVPSizeY();
1054   }
1055   else if (IsActiveXR())
1056   {
1057     aSizeX = myXRSession->RecommendedViewport().x();
1058     aSizeY = myXRSession->RecommendedViewport().y();
1059   }
1060   else
1061   {
1062     aSizeX = myWindow->Width();
1063     aSizeY = myWindow->Height();
1064   }
1065
1066   const Graphic3d_Vec2i aRendSize (Standard_Integer(myRenderParams.RenderResolutionScale * aSizeX + 0.5f),
1067                                    Standard_Integer(myRenderParams.RenderResolutionScale * aSizeY + 0.5f));
1068   if (aSizeX < 1
1069    || aSizeY < 1
1070    || aRendSize.x() < 1
1071    || aRendSize.y() < 1)
1072   {
1073     myBackBufferRestored = Standard_False;
1074     myIsImmediateDrawn   = Standard_False;
1075     return false;
1076   }
1077
1078   // determine multisampling parameters
1079   Standard_Integer aNbSamples = !myToDisableMSAA && aSizeX == aRendSize.x()
1080                               ? Max (Min (myRenderParams.NbMsaaSamples, aCtx->MaxMsaaSamples()), 0)
1081                               : 0;
1082   if (aNbSamples != 0)
1083   {
1084     aNbSamples = OpenGl_Context::GetPowerOfTwo (aNbSamples, aCtx->MaxMsaaSamples());
1085   }
1086
1087   bool toUseOit = myRenderParams.TransparencyMethod != Graphic3d_RTM_BLEND_UNORDERED
1088                && checkOitCompatibility (aCtx, aNbSamples > 0);
1089
1090   const bool toInitImmediateFbo = myTransientDrawToFront
1091                                && (!aCtx->caps->useSystemBuffer || (toUseOit && HasImmediateStructures()));
1092
1093   if ( aFrameBuffer == NULL
1094    && !aCtx->DefaultFrameBuffer().IsNull()
1095    &&  aCtx->DefaultFrameBuffer()->IsValid())
1096   {
1097     aFrameBuffer = aCtx->DefaultFrameBuffer().operator->();
1098   }
1099
1100   if (myHasFboBlit
1101    && (myTransientDrawToFront
1102     || theProj == Graphic3d_Camera::Projection_Stereo
1103     || aNbSamples != 0
1104     || toUseOit
1105     || aSizeX != aRendSize.x()))
1106   {
1107     if (myMainSceneFbos[0]->GetVPSize() != aRendSize
1108      || myMainSceneFbos[0]->NbSamples() != aNbSamples)
1109     {
1110       if (!myTransientDrawToFront)
1111       {
1112         myImmediateSceneFbos[0]->Release (aCtx.operator->());
1113         myImmediateSceneFbos[1]->Release (aCtx.operator->());
1114         myImmediateSceneFbos[0]->ChangeViewport (0, 0);
1115         myImmediateSceneFbos[1]->ChangeViewport (0, 0);
1116       }
1117
1118       // prepare FBOs containing main scene
1119       // for further blitting and rendering immediate presentations on top
1120       if (aCtx->core20fwd != NULL)
1121       {
1122         const bool wasFailedMain0 = checkWasFailedFbo (myMainSceneFbos[0], aRendSize.x(), aRendSize.y(), aNbSamples);
1123         if (!myMainSceneFbos[0]->Init (aCtx, aRendSize, myFboColorFormat, myFboDepthFormat, aNbSamples)
1124          && !wasFailedMain0)
1125         {
1126           TCollection_ExtendedString aMsg = TCollection_ExtendedString() + "Error! Main FBO "
1127                                           + printFboFormat (myMainSceneFbos[0]) + " initialization has failed";
1128           aCtx->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, aMsg);
1129         }
1130       }
1131     }
1132
1133     if (myMainSceneFbos[0]->IsValid() && (toInitImmediateFbo || myImmediateSceneFbos[0]->IsValid()))
1134     {
1135       const bool wasFailedImm0 = checkWasFailedFbo (myImmediateSceneFbos[0], myMainSceneFbos[0]);
1136       if (!myImmediateSceneFbos[0]->InitLazy (aCtx, *myMainSceneFbos[0])
1137        && !wasFailedImm0)
1138       {
1139         TCollection_ExtendedString aMsg = TCollection_ExtendedString() + "Error! Immediate FBO "
1140                                         + printFboFormat (myImmediateSceneFbos[0]) + " initialization has failed";
1141         aCtx->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, aMsg);
1142       }
1143     }
1144   }
1145   else
1146   {
1147     myMainSceneFbos     [0]->Release (aCtx.operator->());
1148     myMainSceneFbos     [1]->Release (aCtx.operator->());
1149     myImmediateSceneFbos[0]->Release (aCtx.operator->());
1150     myImmediateSceneFbos[1]->Release (aCtx.operator->());
1151     myXrSceneFbo           ->Release (aCtx.operator->());
1152     myMainSceneFbos     [0]->ChangeViewport (0, 0);
1153     myMainSceneFbos     [1]->ChangeViewport (0, 0);
1154     myImmediateSceneFbos[0]->ChangeViewport (0, 0);
1155     myImmediateSceneFbos[1]->ChangeViewport (0, 0);
1156     myXrSceneFbo           ->ChangeViewport (0, 0);
1157   }
1158
1159   bool hasXRBlitFbo = false;
1160   if (theProj == Graphic3d_Camera::Projection_Stereo
1161    && IsActiveXR()
1162    && myMainSceneFbos[0]->IsValid())
1163   {
1164     if (aNbSamples != 0
1165      || aSizeX != aRendSize.x())
1166     {
1167       hasXRBlitFbo = myXrSceneFbo->InitLazy (aCtx, Graphic3d_Vec2i (aSizeX, aSizeY), myFboColorFormat, myFboDepthFormat, 0);
1168       if (!hasXRBlitFbo)
1169       {
1170         TCollection_ExtendedString aMsg = TCollection_ExtendedString() + "Error! VR FBO "
1171                                         + printFboFormat (myXrSceneFbo) + " initialization has failed";
1172         aCtx->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, aMsg);
1173       }
1174     }
1175   }
1176   else if (theProj == Graphic3d_Camera::Projection_Stereo
1177         && myMainSceneFbos[0]->IsValid())
1178   {
1179     const bool wasFailedMain1 = checkWasFailedFbo (myMainSceneFbos[1], myMainSceneFbos[0]);
1180     if (!myMainSceneFbos[1]->InitLazy (aCtx, *myMainSceneFbos[0])
1181      && !wasFailedMain1)
1182     {
1183       TCollection_ExtendedString aMsg = TCollection_ExtendedString() + "Error! Main FBO (second) "
1184                                       + printFboFormat (myMainSceneFbos[1]) + " initialization has failed";
1185       aCtx->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, aMsg);
1186     }
1187     if (!myMainSceneFbos[1]->IsValid())
1188     {
1189       // no enough memory?
1190       theProj = Graphic3d_Camera::Projection_Perspective;
1191     }
1192     else if (!myTransientDrawToFront)
1193     {
1194       //
1195     }
1196     else if (!aCtx->HasStereoBuffers()
1197            || myRenderParams.StereoMode != Graphic3d_StereoMode_QuadBuffer)
1198     {
1199       const bool wasFailedImm0 = checkWasFailedFbo (myImmediateSceneFbos[0], myMainSceneFbos[0]);
1200       const bool wasFailedImm1 = checkWasFailedFbo (myImmediateSceneFbos[1], myMainSceneFbos[0]);
1201       if (!myImmediateSceneFbos[0]->InitLazy (aCtx, *myMainSceneFbos[0])
1202        && !wasFailedImm0)
1203       {
1204         TCollection_ExtendedString aMsg = TCollection_ExtendedString() + "Error! Immediate FBO (first) "
1205                                         + printFboFormat (myImmediateSceneFbos[0]) + " initialization has failed";
1206         aCtx->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, aMsg);
1207       }
1208       if (!myImmediateSceneFbos[1]->InitLazy (aCtx, *myMainSceneFbos[0])
1209        && !wasFailedImm1)
1210       {
1211         TCollection_ExtendedString aMsg = TCollection_ExtendedString() + "Error! Immediate FBO (first) "
1212                                         + printFboFormat (myImmediateSceneFbos[1]) + " initialization has failed";
1213         aCtx->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, aMsg);
1214       }
1215       if (!myImmediateSceneFbos[0]->IsValid()
1216        || !myImmediateSceneFbos[1]->IsValid())
1217       {
1218         theProj = Graphic3d_Camera::Projection_Perspective;
1219       }
1220     }
1221   }
1222   if (!hasXRBlitFbo)
1223   {
1224     myXrSceneFbo->Release (aCtx.get());
1225     myXrSceneFbo->ChangeViewport (0, 0);
1226   }
1227
1228   // process PBR environment
1229   if (myRenderParams.ShadingModel == Graphic3d_TypeOfShadingModel_Pbr
1230    || myRenderParams.ShadingModel == Graphic3d_TypeOfShadingModel_PbrFacet)
1231   {
1232     if (!myPBREnvironment.IsNull()
1233       && myPBREnvironment->SizesAreDifferent (myRenderParams.PbrEnvPow2Size,
1234                                               myRenderParams.PbrEnvSpecMapNbLevels))
1235     {
1236       myPBREnvironment->Release (aCtx.get());
1237       myPBREnvironment.Nullify();
1238       myPBREnvState = OpenGl_PBREnvState_NONEXISTENT;
1239       myPBREnvRequest = true;
1240       ++myLightsRevision;
1241     }
1242
1243     if (myPBREnvState == OpenGl_PBREnvState_NONEXISTENT
1244      && aCtx->HasPBR())
1245     {
1246       myPBREnvironment = OpenGl_PBREnvironment::Create (aCtx, myRenderParams.PbrEnvPow2Size, myRenderParams.PbrEnvSpecMapNbLevels);
1247       myPBREnvState = myPBREnvironment.IsNull() ? OpenGl_PBREnvState_UNAVAILABLE : OpenGl_PBREnvState_CREATED;
1248       if (myPBREnvState == OpenGl_PBREnvState_CREATED)
1249       {
1250         Handle(OpenGl_Texture) anEnvLUT;
1251         static const TCollection_AsciiString THE_SHARED_ENV_LUT_KEY("EnvLUT");
1252         if (!aCtx->GetResource (THE_SHARED_ENV_LUT_KEY, anEnvLUT))
1253         {
1254           bool toConvertHalfFloat = false;
1255         #if defined(GL_ES_VERSION_2_0)
1256           // GL_RG32F is not texture-filterable format in OpenGL ES without OES_texture_float_linear extension.
1257           // GL_RG16F is texture-filterable since OpenGL ES 3.0 or OpenGL ES 2.0 + OES_texture_half_float_linear.
1258           // OpenGL ES 3.0 allows initialization of GL_RG16F from 32-bit float data, but OpenGL ES 2.0 + OES_texture_half_float does not.
1259           // Note that it is expected that GL_RG16F has enough precision for this table, so that it can be used also on desktop OpenGL.
1260           const bool hasHalfFloat = aCtx->IsGlGreaterEqual (3, 0) || aCtx->CheckExtension ("GL_OES_texture_half_float_linear");
1261           toConvertHalfFloat = !aCtx->IsGlGreaterEqual (3, 0) && hasHalfFloat;
1262         #endif
1263           Image_Format anImgFormat = Image_Format_UNKNOWN;
1264           if (aCtx->arbTexRG)
1265           {
1266             anImgFormat = toConvertHalfFloat ? Image_Format_RGF_half : Image_Format_RGF;
1267           }
1268           else
1269           {
1270             anImgFormat = toConvertHalfFloat ? Image_Format_RGBAF_half : Image_Format_RGBAF;
1271           }
1272
1273           Handle(Image_PixMap) aPixMap = new Image_PixMap();
1274           if (anImgFormat == Image_Format_RGF)
1275           {
1276             aPixMap->InitWrapper (Image_Format_RGF, (Standard_Byte*)Textures_EnvLUT, Textures_EnvLUTSize, Textures_EnvLUTSize);
1277           }
1278           else
1279           {
1280             aPixMap->InitZero (anImgFormat, Textures_EnvLUTSize, Textures_EnvLUTSize);
1281             Image_PixMap aPixMapRG;
1282             aPixMapRG.InitWrapper (Image_Format_RGF, (Standard_Byte*)Textures_EnvLUT, Textures_EnvLUTSize, Textures_EnvLUTSize);
1283             for (Standard_Size aRowIter = 0; aRowIter < aPixMapRG.SizeY(); ++aRowIter)
1284             {
1285               for (Standard_Size aColIter = 0; aColIter < aPixMapRG.SizeX(); ++aColIter)
1286               {
1287                 const Image_ColorRGF& aPixelRG = aPixMapRG.Value<Image_ColorRGF> (aRowIter, aColIter);
1288                 if (toConvertHalfFloat)
1289                 {
1290                   NCollection_Vec2<uint16_t>& aPixelRGBA = aPixMap->ChangeValue<NCollection_Vec2<uint16_t>> (aRowIter, aColIter);
1291                   aPixelRGBA.x() = Image_PixMap::ConvertToHalfFloat (aPixelRG.r());
1292                   aPixelRGBA.y() = Image_PixMap::ConvertToHalfFloat (aPixelRG.g());
1293                 }
1294                 else
1295                 {
1296                   Image_ColorRGBAF& aPixelRGBA = aPixMap->ChangeValue<Image_ColorRGBAF> (aRowIter, aColIter);
1297                   aPixelRGBA.r() = aPixelRG.r();
1298                   aPixelRGBA.g() = aPixelRG.g();
1299                 }
1300               }
1301             }
1302           }
1303
1304           OpenGl_TextureFormat aTexFormat = OpenGl_TextureFormat::FindFormat (aCtx, aPixMap->Format(), false);
1305         #if defined(GL_ES_VERSION_2_0)
1306           if (aTexFormat.IsValid()
1307            && hasHalfFloat)
1308           {
1309             aTexFormat.SetInternalFormat (aCtx->arbTexRG ? GL_RG16F : GL_RGBA16F);
1310           }
1311         #endif
1312
1313           Handle(Graphic3d_TextureParams) aParams = new Graphic3d_TextureParams();
1314           aParams->SetFilter (Graphic3d_TOTF_BILINEAR);
1315           aParams->SetRepeat (Standard_False);
1316           aParams->SetTextureUnit (aCtx->PBREnvLUTTexUnit());
1317           anEnvLUT = new OpenGl_Texture(THE_SHARED_ENV_LUT_KEY, aParams);
1318           if (!aTexFormat.IsValid()
1319            || !anEnvLUT->Init (aCtx, aTexFormat, Graphic3d_Vec2i((Standard_Integer)Textures_EnvLUTSize), Graphic3d_TOT_2D, aPixMap.get()))
1320           {
1321             aCtx->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, "Failed allocation of LUT for PBR");
1322             anEnvLUT.Nullify();
1323           }
1324           aCtx->ShareResource (THE_SHARED_ENV_LUT_KEY, anEnvLUT);
1325         }
1326         if (!anEnvLUT.IsNull())
1327         {
1328           anEnvLUT->Bind (aCtx);
1329         }
1330         myWorkspace->ApplyAspects();
1331       }
1332     }
1333     updatePBREnvironment (aCtx);
1334   }
1335
1336   // create color and coverage accumulation buffers required for OIT algorithm
1337   if (toUseOit
1338    && myRenderParams.TransparencyMethod == Graphic3d_RTM_DEPTH_PEELING_OIT)
1339   {
1340     if (myDepthPeelingFbos->BlendBackFboOit()->GetSize() != aRendSize)
1341     {
1342       if (myDepthPeelingFbos->BlendBackFboOit()->Init (aCtx, aRendSize, GL_RGBA16F, 0))
1343       {
1344         for (int aPairIter = 0; aPairIter < 2; ++aPairIter)
1345         {
1346           OpenGl_ColorFormats aColorFormats;
1347           aColorFormats.Append (GL_RG32F);
1348           aColorFormats.Append (GL_RGBA16F);
1349           aColorFormats.Append (GL_RGBA16F);
1350           myDepthPeelingFbos->DepthPeelFbosOit()[aPairIter]->Init (aCtx, aRendSize, aColorFormats, 0);
1351
1352           NCollection_Sequence<Handle(OpenGl_Texture)> anAttachments;
1353           anAttachments.Append (myDepthPeelingFbos->DepthPeelFbosOit()[aPairIter]->ColorTexture (1));
1354           anAttachments.Append (myDepthPeelingFbos->DepthPeelFbosOit()[aPairIter]->ColorTexture (2));
1355           myDepthPeelingFbos->FrontBackColorFbosOit()[aPairIter]->InitWrapper (aCtx, anAttachments);
1356         }
1357       }
1358       else
1359       {
1360         toUseOit = false;
1361         aCtx->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH,
1362                            "Initialization of float texture framebuffer for use with\n"
1363                            "  Depth-Peeling order-independent transparency rendering algorithm has failed.");
1364       }
1365     }
1366   }
1367   if (!toUseOit)
1368   {
1369     myDepthPeelingFbos->Release (aCtx.operator->());
1370   }
1371
1372   if (toUseOit
1373    && myRenderParams.TransparencyMethod == Graphic3d_RTM_BLEND_OIT)
1374   {
1375     Standard_Integer anFboIt = 0;
1376     for (; anFboIt < 2; ++anFboIt)
1377     {
1378       Handle(OpenGl_FrameBuffer)& aMainSceneFbo          = myMainSceneFbos        [anFboIt];
1379       Handle(OpenGl_FrameBuffer)& aMainSceneFboOit       = myMainSceneFbosOit     [anFboIt];
1380       Handle(OpenGl_FrameBuffer)& anImmediateSceneFbo    = myImmediateSceneFbos   [anFboIt];
1381       Handle(OpenGl_FrameBuffer)& anImmediateSceneFboOit = myImmediateSceneFbosOit[anFboIt];
1382       if (aMainSceneFbo->IsValid()
1383        && (aMainSceneFboOit->GetVPSize() != aRendSize
1384         || aMainSceneFboOit->NbSamples() != aNbSamples))
1385       {
1386         Standard_Integer aColorConfig = 0;
1387         for (;;) // seemly responding to driver limitation (GL_FRAMEBUFFER_UNSUPPORTED)
1388         {
1389           if (myFboOitColorConfig.IsEmpty())
1390           {
1391             if (!chooseOitColorConfiguration (aCtx, aColorConfig++, myFboOitColorConfig))
1392             {
1393               break;
1394             }
1395           }
1396           if (aMainSceneFboOit->Init (aCtx, aRendSize, myFboOitColorConfig, aMainSceneFbo->DepthStencilTexture(), aNbSamples))
1397           {
1398             break;
1399           }
1400           myFboOitColorConfig.Clear();
1401         }
1402         if (!aMainSceneFboOit->IsValid())
1403         {
1404           break;
1405         }
1406       }
1407       else if (!aMainSceneFbo->IsValid())
1408       {
1409         aMainSceneFboOit->Release (aCtx.operator->());
1410         aMainSceneFboOit->ChangeViewport (0, 0);
1411       }
1412
1413       if (anImmediateSceneFbo->IsValid()
1414        && (anImmediateSceneFboOit->GetVPSize() != aRendSize
1415         || anImmediateSceneFboOit->NbSamples() != aNbSamples))
1416       {
1417         if (!anImmediateSceneFboOit->Init (aCtx, aRendSize, myFboOitColorConfig,
1418                                            anImmediateSceneFbo->DepthStencilTexture(), aNbSamples))
1419         {
1420           break;
1421         }
1422       }
1423       else if (!anImmediateSceneFbo->IsValid())
1424       {
1425         anImmediateSceneFboOit->Release (aCtx.operator->());
1426         anImmediateSceneFboOit->ChangeViewport (0, 0);
1427       }
1428     }
1429     if (anFboIt == 0) // only the first OIT framebuffer is mandatory
1430     {
1431       aCtx->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH,
1432                          "Initialization of float texture framebuffer for use with\n"
1433                          "  blended order-independent transparency rendering algorithm has failed.\n"
1434                          "  Blended order-independent transparency will not be available.\n");
1435       if (aNbSamples > 0)
1436       {
1437         myToDisableOITMSAA = Standard_True;
1438       }
1439       else
1440       {
1441         myToDisableOIT     = Standard_True;
1442       }
1443       toUseOit = false;
1444     }
1445   }
1446   if (!toUseOit && myMainSceneFbosOit[0]->IsValid())
1447   {
1448     myDepthPeelingFbos->Release (aCtx.operator->());
1449     myMainSceneFbosOit     [0]->Release (aCtx.operator->());
1450     myMainSceneFbosOit     [1]->Release (aCtx.operator->());
1451     myImmediateSceneFbosOit[0]->Release (aCtx.operator->());
1452     myImmediateSceneFbosOit[1]->Release (aCtx.operator->());
1453     myMainSceneFbosOit     [0]->ChangeViewport (0, 0);
1454     myMainSceneFbosOit     [1]->ChangeViewport (0, 0);
1455     myImmediateSceneFbosOit[0]->ChangeViewport (0, 0);
1456     myImmediateSceneFbosOit[1]->ChangeViewport (0, 0);
1457   }
1458
1459   // allocate shadow maps
1460   const Handle(Graphic3d_LightSet)& aLights = myRenderParams.ShadingModel == Graphic3d_TypeOfShadingModel_Unlit ? myNoShadingLight : myLights;
1461   if (!aLights.IsNull())
1462   {
1463     aLights->UpdateRevision();
1464   }
1465   bool toUseShadowMap = myRenderParams.IsShadowEnabled
1466                      && myRenderParams.ShadowMapResolution > 0
1467                      && !myLights.IsNull()
1468                      && myLights->NbCastShadows() > 0
1469                      && myRenderParams.Method != Graphic3d_RM_RAYTRACING;
1470   if (toUseShadowMap)
1471   {
1472     if (myShadowMaps->Size() != myLights->NbCastShadows())
1473     {
1474       myShadowMaps->Release (aCtx.get());
1475       myShadowMaps->Resize (0, myLights->NbCastShadows() - 1, true);
1476     }
1477
1478     const GLint aSamplFrom = GLint(aCtx->ShadowMapTexUnit()) - myLights->NbCastShadows() + 1;
1479     for (Standard_Integer aShadowIter = 0; aShadowIter < myShadowMaps->Size(); ++aShadowIter)
1480     {
1481       Handle(OpenGl_ShadowMap)& aShadow = myShadowMaps->ChangeValue (aShadowIter);
1482       if (aShadow.IsNull())
1483       {
1484         aShadow = new OpenGl_ShadowMap();
1485       }
1486       aShadow->SetShadowMapBias (myRenderParams.ShadowMapBias);
1487       aShadow->Texture()->Sampler()->Parameters()->SetTextureUnit ((Graphic3d_TextureUnit )(aSamplFrom + aShadowIter));
1488
1489       const Handle(OpenGl_FrameBuffer)& aShadowFbo = aShadow->FrameBuffer();
1490       if (aShadowFbo->GetVPSizeX() != myRenderParams.ShadowMapResolution
1491        && toUseShadowMap)
1492       {
1493         OpenGl_ColorFormats aDummy;
1494         if (!aShadowFbo->Init (aCtx, Graphic3d_Vec2i (myRenderParams.ShadowMapResolution), aDummy, myFboDepthFormat, 0))
1495         {
1496           toUseShadowMap = false;
1497         }
1498       }
1499     }
1500   }
1501   if (!toUseShadowMap && myShadowMaps->IsValid())
1502   {
1503     myShadowMaps->Release (aCtx.get());
1504   }
1505
1506   return true;
1507 }
1508
1509 //=======================================================================
1510 //function : Redraw
1511 //purpose  :
1512 //=======================================================================
1513 void OpenGl_View::Redraw()
1514 {
1515   const Standard_Boolean wasDisabledMSAA = myToDisableMSAA;
1516   const Standard_Boolean hadFboBlit      = myHasFboBlit;
1517   if (myRenderParams.Method == Graphic3d_RM_RAYTRACING
1518   && !myCaps->vboDisable
1519   && !myCaps->keepArrayData)
1520   {
1521     // caps are shared across all views, thus we need to invalidate all of them
1522     // if (myWasRedrawnGL) { myStructureManager->SetDeviceLost(); }
1523     myDriver->setDeviceLost();
1524     myCaps->keepArrayData = Standard_True;
1525   }
1526
1527   if (!myWorkspace->Activate())
1528   {
1529     return;
1530   }
1531
1532   // implicitly disable VSync when using HMD composer (can be mirrored in window for debugging)
1533   myWindow->SetSwapInterval (IsActiveXR());
1534
1535   ++myFrameCounter;
1536   const Handle(OpenGl_Context)& aCtx = myWorkspace->GetGlContext();
1537   aCtx->FrameStats()->FrameStart (myWorkspace->View(), false);
1538   aCtx->SetLineFeather (myRenderParams.LineFeather);
1539
1540   const Standard_Integer anSRgbState = aCtx->ToRenderSRGB() ? 1 : 0;
1541   if (mySRgbState != -1
1542    && mySRgbState != anSRgbState)
1543   {
1544     releaseSrgbResources (aCtx);
1545     initTextureEnv (aCtx);
1546   }
1547   mySRgbState = anSRgbState;
1548   aCtx->ShaderManager()->UpdateSRgbState();
1549
1550   // release pending GL resources
1551   aCtx->ReleaseDelayed();
1552
1553   // fetch OpenGl context state
1554   aCtx->FetchState();
1555
1556   const Graphic3d_StereoMode   aStereoMode  = myRenderParams.StereoMode;
1557   Graphic3d_Camera::Projection aProjectType = myCamera->ProjectionType();
1558   if (!prepareFrameBuffers (aProjectType))
1559   {
1560     myBackBufferRestored = Standard_False;
1561     myIsImmediateDrawn   = Standard_False;
1562     return;
1563   }
1564
1565   // draw shadow maps
1566   if (myShadowMaps->IsValid())
1567   {
1568     Standard_Integer aShadowIndex = myShadowMaps->Lower();
1569     for (Graphic3d_LightSet::Iterator aLightIter (myLights, Graphic3d_LightSet::IterationFilter_ActiveShadowCasters);
1570          aLightIter.More(); aLightIter.Next())
1571     {
1572       const Handle(Graphic3d_CLight)& aLight = aLightIter.Value();
1573       if (aLight->ToCastShadows())
1574       {
1575         const Handle(OpenGl_ShadowMap)& aShadowMap = myShadowMaps->ChangeValue (aShadowIndex);
1576         aShadowMap->SetLightSource (aLight);
1577         renderShadowMap (aShadowMap);
1578         ++aShadowIndex;
1579       }
1580     }
1581     for (; aShadowIndex <= myShadowMaps->Upper(); ++aShadowIndex)
1582     {
1583       myShadowMaps->ChangeValue (aShadowIndex)->SetLightSource (Handle(Graphic3d_CLight)());
1584     }
1585   }
1586
1587   OpenGl_FrameBuffer* aFrameBuffer = myFBO.get();
1588   bool toSwap = aCtx->IsRender()
1589             && !aCtx->caps->buffersNoSwap
1590             &&  aFrameBuffer == NULL
1591             &&  (!IsActiveXR() || myRenderParams.ToMirrorComposer);
1592   if ( aFrameBuffer == NULL
1593    && !aCtx->DefaultFrameBuffer().IsNull()
1594    &&  aCtx->DefaultFrameBuffer()->IsValid())
1595   {
1596     aFrameBuffer = aCtx->DefaultFrameBuffer().operator->();
1597   }
1598
1599   if (aProjectType == Graphic3d_Camera::Projection_Stereo)
1600   {
1601     OpenGl_FrameBuffer* aMainFbos[2] =
1602     {
1603       myMainSceneFbos[0]->IsValid() ? myMainSceneFbos[0].operator->() : NULL,
1604       myMainSceneFbos[1]->IsValid() ? myMainSceneFbos[1].operator->() : NULL
1605     };
1606     OpenGl_FrameBuffer* aMainFbosOit[2] =
1607     {
1608       myMainSceneFbosOit[0]->IsValid() ? myMainSceneFbosOit[0].operator->() : NULL,
1609       myMainSceneFbosOit[1]->IsValid() ? myMainSceneFbosOit[1].operator->() :
1610         myMainSceneFbosOit[0]->IsValid() ? myMainSceneFbosOit[0].operator->() : NULL
1611     };
1612
1613     OpenGl_FrameBuffer* anImmFbos[2] =
1614     {
1615       myImmediateSceneFbos[0]->IsValid() ? myImmediateSceneFbos[0].operator->() : NULL,
1616       myImmediateSceneFbos[1]->IsValid() ? myImmediateSceneFbos[1].operator->() : NULL
1617     };
1618     OpenGl_FrameBuffer* anImmFbosOit[2] =
1619     {
1620       myImmediateSceneFbosOit[0]->IsValid() ? myImmediateSceneFbosOit[0].operator->() : NULL,
1621       myImmediateSceneFbosOit[1]->IsValid() ? myImmediateSceneFbosOit[1].operator->() :
1622         myImmediateSceneFbosOit[0]->IsValid() ? myImmediateSceneFbosOit[0].operator->() : NULL
1623     };
1624
1625     if (IsActiveXR())
1626     {
1627       // use single frame for both views - caching main scene content makes no sense
1628       // when head position is expected to be updated each frame redraw with high accuracy
1629       aMainFbos[1]    = aMainFbos[0];
1630       aMainFbosOit[1] = aMainFbosOit[0];
1631       anImmFbos[0]    = aMainFbos[0];
1632       anImmFbos[1]    = aMainFbos[1];
1633       anImmFbosOit[0] = aMainFbosOit[0];
1634       anImmFbosOit[1] = aMainFbosOit[1];
1635     }
1636     else if (!myTransientDrawToFront)
1637     {
1638       anImmFbos   [0] = aMainFbos   [0];
1639       anImmFbos   [1] = aMainFbos   [1];
1640       anImmFbosOit[0] = aMainFbosOit[0];
1641       anImmFbosOit[1] = aMainFbosOit[1];
1642     }
1643     else if (aStereoMode == Graphic3d_StereoMode_SoftPageFlip
1644           || aStereoMode == Graphic3d_StereoMode_QuadBuffer)
1645     {
1646       anImmFbos   [0] = NULL;
1647       anImmFbos   [1] = NULL;
1648       anImmFbosOit[0] = NULL;
1649       anImmFbosOit[1] = NULL;
1650     }
1651
1652   #if !defined(GL_ES_VERSION_2_0)
1653     aCtx->SetReadDrawBuffer (aStereoMode == Graphic3d_StereoMode_QuadBuffer ? GL_BACK_LEFT : GL_BACK);
1654   #endif
1655     aCtx->SetResolution (myRenderParams.Resolution, myRenderParams.ResolutionRatio(),
1656                          aMainFbos[0] != NULL ? myRenderParams.RenderResolutionScale : 1.0f);
1657
1658     redraw (Graphic3d_Camera::Projection_MonoLeftEye, aMainFbos[0], aMainFbosOit[0]);
1659     myBackBufferRestored = Standard_True;
1660     myIsImmediateDrawn   = Standard_False;
1661   #if !defined(GL_ES_VERSION_2_0)
1662     aCtx->SetReadDrawBuffer (aStereoMode == Graphic3d_StereoMode_QuadBuffer ? GL_BACK_LEFT : GL_BACK);
1663   #endif
1664     aCtx->SetResolution (myRenderParams.Resolution, myRenderParams.ResolutionRatio(),
1665                          anImmFbos[0] != NULL ? myRenderParams.RenderResolutionScale : 1.0f);
1666     if (!redrawImmediate (Graphic3d_Camera::Projection_MonoLeftEye, aMainFbos[0], anImmFbos[0], anImmFbosOit[0]))
1667     {
1668       toSwap = false;
1669     }
1670     else if (aStereoMode == Graphic3d_StereoMode_SoftPageFlip && toSwap)
1671     {
1672       aCtx->SwapBuffers();
1673     }
1674
1675     if (IsActiveXR())
1676     {
1677       // push Left frame to HMD display composer
1678       OpenGl_FrameBuffer* anXRFbo = myXrSceneFbo->IsValid() ? myXrSceneFbo.get() : aMainFbos[0];
1679       if (anXRFbo != aMainFbos[0])
1680       {
1681         blitBuffers (aMainFbos[0], anXRFbo); // resize or resolve MSAA samples
1682       }
1683     #if !defined(GL_ES_VERSION_2_0)
1684       const Aspect_GraphicsLibrary aGraphicsLib = Aspect_GraphicsLibrary_OpenGL;
1685     #else
1686       const Aspect_GraphicsLibrary aGraphicsLib = Aspect_GraphicsLibrary_OpenGLES;
1687     #endif
1688       myXRSession->SubmitEye ((void* )(size_t )anXRFbo->ColorTexture()->TextureId(),
1689                               aGraphicsLib, Aspect_ColorSpace_sRGB, Aspect_Eye_Left);
1690     }
1691
1692   #if !defined(GL_ES_VERSION_2_0)
1693     aCtx->SetReadDrawBuffer (aStereoMode == Graphic3d_StereoMode_QuadBuffer ? GL_BACK_RIGHT : GL_BACK);
1694   #endif
1695     aCtx->SetResolution (myRenderParams.Resolution, myRenderParams.ResolutionRatio(),
1696                          aMainFbos[1] != NULL ? myRenderParams.RenderResolutionScale : 1.0f);
1697
1698     redraw (Graphic3d_Camera::Projection_MonoRightEye, aMainFbos[1], aMainFbosOit[1]);
1699     myBackBufferRestored = Standard_True;
1700     myIsImmediateDrawn   = Standard_False;
1701     aCtx->SetResolution (myRenderParams.Resolution, myRenderParams.ResolutionRatio(),
1702                          anImmFbos[1] != NULL ? myRenderParams.RenderResolutionScale : 1.0f);
1703     if (!redrawImmediate (Graphic3d_Camera::Projection_MonoRightEye, aMainFbos[1], anImmFbos[1], anImmFbosOit[1]))
1704     {
1705       toSwap = false;
1706     }
1707
1708     if (IsActiveXR())
1709     {
1710       // push Right frame to HMD display composer
1711       OpenGl_FrameBuffer* anXRFbo = myXrSceneFbo->IsValid() ? myXrSceneFbo.get() : aMainFbos[1];
1712       if (anXRFbo != aMainFbos[1])
1713       {
1714         blitBuffers (aMainFbos[1], anXRFbo); // resize or resolve MSAA samples
1715       }
1716     #if !defined(GL_ES_VERSION_2_0)
1717       const Aspect_GraphicsLibrary aGraphicsLib = Aspect_GraphicsLibrary_OpenGL;
1718     #else
1719       const Aspect_GraphicsLibrary aGraphicsLib = Aspect_GraphicsLibrary_OpenGLES;
1720     #endif
1721       myXRSession->SubmitEye ((void* )(size_t )anXRFbo->ColorTexture()->TextureId(),
1722                               aGraphicsLib, Aspect_ColorSpace_sRGB, Aspect_Eye_Right);
1723       aCtx->core11fwd->glFinish();
1724
1725       if (myRenderParams.ToMirrorComposer)
1726       {
1727         blitBuffers (anXRFbo, aFrameBuffer, myToFlipOutput);
1728       }
1729     }
1730     else if (anImmFbos[0] != NULL)
1731     {
1732       aCtx->SetResolution (myRenderParams.Resolution, myRenderParams.ResolutionRatio(), 1.0f);
1733       drawStereoPair (aFrameBuffer);
1734     }
1735   }
1736   else
1737   {
1738     OpenGl_FrameBuffer* aMainFbo    = myMainSceneFbos[0]->IsValid() ? myMainSceneFbos[0].operator->() : aFrameBuffer;
1739     OpenGl_FrameBuffer* aMainFboOit = myMainSceneFbosOit[0]->IsValid() ? myMainSceneFbosOit[0].operator->() : NULL;
1740     OpenGl_FrameBuffer* anImmFbo    = aFrameBuffer;
1741     OpenGl_FrameBuffer* anImmFboOit = NULL;
1742     if (!myTransientDrawToFront)
1743     {
1744       anImmFbo    = aMainFbo;
1745       anImmFboOit = aMainFboOit;
1746     }
1747     else if (myImmediateSceneFbos[0]->IsValid())
1748     {
1749       anImmFbo    = myImmediateSceneFbos[0].operator->();
1750       anImmFboOit = myImmediateSceneFbosOit[0]->IsValid() ? myImmediateSceneFbosOit[0].operator->() : NULL;
1751     }
1752
1753   #if !defined(GL_ES_VERSION_2_0)
1754     if (aMainFbo == NULL)
1755     {
1756       aCtx->SetReadDrawBuffer (GL_BACK);
1757     }
1758   #endif
1759     aCtx->SetResolution (myRenderParams.Resolution, myRenderParams.ResolutionRatio(),
1760                          aMainFbo != aFrameBuffer ? myRenderParams.RenderResolutionScale : 1.0f);
1761
1762     redraw (aProjectType, aMainFbo, aMainFboOit);
1763     myBackBufferRestored = Standard_True;
1764     myIsImmediateDrawn   = Standard_False;
1765     aCtx->SetResolution (myRenderParams.Resolution, myRenderParams.ResolutionRatio(),
1766                          anImmFbo != aFrameBuffer ? myRenderParams.RenderResolutionScale : 1.0f);
1767     if (!redrawImmediate (aProjectType, aMainFbo, anImmFbo, anImmFboOit))
1768     {
1769       toSwap = false;
1770     }
1771
1772     if (anImmFbo != NULL
1773      && anImmFbo != aFrameBuffer)
1774     {
1775       blitBuffers (anImmFbo, aFrameBuffer, myToFlipOutput);
1776     }
1777   }
1778
1779   if (myRenderParams.Method == Graphic3d_RM_RAYTRACING
1780    && myRenderParams.IsGlobalIlluminationEnabled)
1781   {
1782     myAccumFrames++;
1783   }
1784
1785   // bind default FBO
1786   bindDefaultFbo();
1787
1788   if (wasDisabledMSAA != myToDisableMSAA
1789    || hadFboBlit      != myHasFboBlit)
1790   {
1791     // retry on error
1792     Redraw();
1793   }
1794
1795   // reset state for safety
1796   aCtx->BindProgram (Handle(OpenGl_ShaderProgram)());
1797   if (aCtx->caps->ffpEnable)
1798   {
1799     aCtx->ShaderManager()->PushState (Handle(OpenGl_ShaderProgram)());
1800   }
1801
1802   // Swap the buffers
1803   if (toSwap)
1804   {
1805     aCtx->SwapBuffers();
1806     if (!myMainSceneFbos[0]->IsValid())
1807     {
1808       myBackBufferRestored = Standard_False;
1809     }
1810   }
1811   else
1812   {
1813     aCtx->core11fwd->glFlush();
1814   }
1815
1816   // reset render mode state
1817   aCtx->FetchState();
1818   aCtx->FrameStats()->FrameEnd (myWorkspace->View(), false);
1819
1820   myWasRedrawnGL = Standard_True;
1821 }
1822
1823 // =======================================================================
1824 // function : RedrawImmediate
1825 // purpose  :
1826 // =======================================================================
1827 void OpenGl_View::RedrawImmediate()
1828 {
1829   if (!myWorkspace->Activate())
1830     return;
1831
1832   // no special handling of HMD display, since it will force full Redraw() due to no frame caching (myBackBufferRestored)
1833   Handle(OpenGl_Context) aCtx = myWorkspace->GetGlContext();
1834   if (!myTransientDrawToFront
1835    || !myBackBufferRestored
1836    || (aCtx->caps->buffersNoSwap && !myMainSceneFbos[0]->IsValid()))
1837   {
1838     Redraw();
1839     return;
1840   }
1841
1842   const Graphic3d_StereoMode   aStereoMode  = myRenderParams.StereoMode;
1843   Graphic3d_Camera::Projection aProjectType = myCamera->ProjectionType();
1844   OpenGl_FrameBuffer*          aFrameBuffer = myFBO.get();
1845   aCtx->FrameStats()->FrameStart (myWorkspace->View(), true);
1846
1847   if ( aFrameBuffer == NULL
1848    && !aCtx->DefaultFrameBuffer().IsNull()
1849    &&  aCtx->DefaultFrameBuffer()->IsValid())
1850   {
1851     aFrameBuffer = aCtx->DefaultFrameBuffer().operator->();
1852   }
1853
1854   if (aProjectType == Graphic3d_Camera::Projection_Stereo)
1855   {
1856     if (myMainSceneFbos[0]->IsValid()
1857     && !myMainSceneFbos[1]->IsValid())
1858     {
1859       aProjectType = Graphic3d_Camera::Projection_Perspective;
1860     }
1861   }
1862
1863   bool toSwap = false;
1864   if (aProjectType == Graphic3d_Camera::Projection_Stereo)
1865   {
1866     OpenGl_FrameBuffer* aMainFbos[2] =
1867     {
1868       myMainSceneFbos[0]->IsValid() ? myMainSceneFbos[0].operator->() : NULL,
1869       myMainSceneFbos[1]->IsValid() ? myMainSceneFbos[1].operator->() : NULL
1870     };
1871     OpenGl_FrameBuffer* anImmFbos[2] =
1872     {
1873       myImmediateSceneFbos[0]->IsValid() ? myImmediateSceneFbos[0].operator->() : NULL,
1874       myImmediateSceneFbos[1]->IsValid() ? myImmediateSceneFbos[1].operator->() : NULL
1875     };
1876     OpenGl_FrameBuffer* anImmFbosOit[2] =
1877     {
1878       myImmediateSceneFbosOit[0]->IsValid() ? myImmediateSceneFbosOit[0].operator->() : NULL,
1879       myImmediateSceneFbosOit[1]->IsValid() ? myImmediateSceneFbosOit[1].operator->() :
1880         myImmediateSceneFbosOit[0]->IsValid() ? myImmediateSceneFbosOit[0].operator->() : NULL
1881     };
1882     if (aStereoMode == Graphic3d_StereoMode_SoftPageFlip
1883      || aStereoMode == Graphic3d_StereoMode_QuadBuffer)
1884     {
1885       anImmFbos[0]    = NULL;
1886       anImmFbos[1]    = NULL;
1887       anImmFbosOit[0] = NULL;
1888       anImmFbosOit[1] = NULL;
1889     }
1890
1891     if (aCtx->arbFBO != NULL)
1892     {
1893       aCtx->arbFBO->glBindFramebuffer (GL_FRAMEBUFFER, OpenGl_FrameBuffer::NO_FRAMEBUFFER);
1894     }
1895   #if !defined(GL_ES_VERSION_2_0)
1896     if (anImmFbos[0] == NULL)
1897     {
1898       aCtx->SetReadDrawBuffer (aStereoMode == Graphic3d_StereoMode_QuadBuffer ? GL_BACK_LEFT : GL_BACK);
1899     }
1900   #endif
1901
1902     aCtx->SetResolution (myRenderParams.Resolution, myRenderParams.ResolutionRatio(),
1903                          anImmFbos[0] != NULL ? myRenderParams.RenderResolutionScale : 1.0f);
1904     toSwap = redrawImmediate (Graphic3d_Camera::Projection_MonoLeftEye,
1905                               aMainFbos[0],
1906                               anImmFbos[0],
1907                               anImmFbosOit[0],
1908                               Standard_True) || toSwap;
1909     if (aStereoMode == Graphic3d_StereoMode_SoftPageFlip
1910     &&  toSwap
1911     &&  myFBO.get() == NULL
1912     && !aCtx->caps->buffersNoSwap)
1913     {
1914       aCtx->SwapBuffers();
1915     }
1916
1917     if (aCtx->arbFBO != NULL)
1918     {
1919       aCtx->arbFBO->glBindFramebuffer (GL_FRAMEBUFFER, OpenGl_FrameBuffer::NO_FRAMEBUFFER);
1920     }
1921   #if !defined(GL_ES_VERSION_2_0)
1922     if (anImmFbos[1] == NULL)
1923     {
1924       aCtx->SetReadDrawBuffer (aStereoMode == Graphic3d_StereoMode_QuadBuffer ? GL_BACK_RIGHT : GL_BACK);
1925     }
1926   #endif
1927     aCtx->SetResolution (myRenderParams.Resolution, myRenderParams.ResolutionRatio(),
1928                          anImmFbos[1] != NULL ? myRenderParams.RenderResolutionScale : 1.0f);
1929     toSwap = redrawImmediate (Graphic3d_Camera::Projection_MonoRightEye,
1930                               aMainFbos[1],
1931                               anImmFbos[1],
1932                               anImmFbosOit[1],
1933                               Standard_True) || toSwap;
1934     if (anImmFbos[0] != NULL)
1935     {
1936       drawStereoPair (aFrameBuffer);
1937     }
1938   }
1939   else
1940   {
1941     OpenGl_FrameBuffer* aMainFbo = myMainSceneFbos[0]->IsValid() ? myMainSceneFbos[0].operator->() : NULL;
1942     OpenGl_FrameBuffer* anImmFbo = aFrameBuffer;
1943     OpenGl_FrameBuffer* anImmFboOit = NULL;
1944     if (myImmediateSceneFbos[0]->IsValid())
1945     {
1946       anImmFbo    = myImmediateSceneFbos[0].operator->();
1947       anImmFboOit = myImmediateSceneFbosOit[0]->IsValid() ? myImmediateSceneFbosOit[0].operator->() : NULL;
1948     }
1949   #if !defined(GL_ES_VERSION_2_0)
1950     if (aMainFbo == NULL)
1951     {
1952       aCtx->SetReadDrawBuffer (GL_BACK);
1953     }
1954   #endif
1955     aCtx->SetResolution (myRenderParams.Resolution, myRenderParams.ResolutionRatio(),
1956                          anImmFbo != aFrameBuffer ? myRenderParams.RenderResolutionScale : 1.0f);
1957     toSwap = redrawImmediate (aProjectType,
1958                               aMainFbo,
1959                               anImmFbo,
1960                               anImmFboOit,
1961                               Standard_True) || toSwap;
1962     if (anImmFbo != NULL
1963      && anImmFbo != aFrameBuffer)
1964     {
1965       blitBuffers (anImmFbo, aFrameBuffer, myToFlipOutput);
1966     }
1967   }
1968
1969   // bind default FBO
1970   bindDefaultFbo();
1971
1972   // reset state for safety
1973   aCtx->BindProgram (Handle(OpenGl_ShaderProgram)());
1974   if (aCtx->caps->ffpEnable)
1975   {
1976     aCtx->ShaderManager()->PushState (Handle(OpenGl_ShaderProgram)());
1977   }
1978
1979   if (toSwap
1980   &&  myFBO.get() == NULL
1981   && !aCtx->caps->buffersNoSwap)
1982   {
1983     aCtx->SwapBuffers();
1984   }
1985   else
1986   {
1987     aCtx->core11fwd->glFlush();
1988   }
1989   aCtx->FrameStats()->FrameEnd (myWorkspace->View(), true);
1990
1991   myWasRedrawnGL = Standard_True;
1992 }
1993
1994 // =======================================================================
1995 // function : redraw
1996 // purpose  :
1997 // =======================================================================
1998 void OpenGl_View::redraw (const Graphic3d_Camera::Projection theProjection,
1999                           OpenGl_FrameBuffer*                theReadDrawFbo,
2000                           OpenGl_FrameBuffer*                theOitAccumFbo)
2001 {
2002   Handle(OpenGl_Context) aCtx = myWorkspace->GetGlContext();
2003   if (theReadDrawFbo != NULL)
2004   {
2005     theReadDrawFbo->BindBuffer    (aCtx);
2006     theReadDrawFbo->SetupViewport (aCtx);
2007   }
2008   else
2009   {
2010     const Standard_Integer aViewport[4] = { 0, 0, myWindow->Width(), myWindow->Height() };
2011     aCtx->ResizeViewport (aViewport);
2012   }
2013
2014   // request reset of material
2015   aCtx->ShaderManager()->UpdateMaterialState();
2016
2017   myWorkspace->UseZBuffer()    = Standard_True;
2018   myWorkspace->UseDepthWrite() = Standard_True;
2019   GLbitfield toClear = GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT;
2020   aCtx->core11fwd->glDepthFunc (GL_LEQUAL);
2021   aCtx->core11fwd->glDepthMask (GL_TRUE);
2022   aCtx->core11fwd->glEnable (GL_DEPTH_TEST);
2023
2024   aCtx->core11fwd->glClearDepth (1.0);
2025
2026   const OpenGl_Vec4 aBgColor = aCtx->Vec4FromQuantityColor (myBgColor);
2027   aCtx->SetColorMaskRGBA (NCollection_Vec4<bool> (true)); // force writes into all components, including alpha
2028   aCtx->core11fwd->glClearColor (aBgColor.r(), aBgColor.g(), aBgColor.b(), aCtx->caps->buffersOpaqueAlpha ? 1.0f : 0.0f);
2029   aCtx->core11fwd->glClear (toClear);
2030   aCtx->SetColorMask (true); // restore default alpha component write state
2031
2032   render (theProjection, theReadDrawFbo, theOitAccumFbo, Standard_False);
2033 }
2034
2035 // =======================================================================
2036 // function : redrawImmediate
2037 // purpose  :
2038 // =======================================================================
2039 bool OpenGl_View::redrawImmediate (const Graphic3d_Camera::Projection theProjection,
2040                                    OpenGl_FrameBuffer*                theReadFbo,
2041                                    OpenGl_FrameBuffer*                theDrawFbo,
2042                                    OpenGl_FrameBuffer*                theOitAccumFbo,
2043                                    const Standard_Boolean             theIsPartialUpdate)
2044 {
2045   const Handle(OpenGl_Context)& aCtx = myWorkspace->GetGlContext();
2046   GLboolean toCopyBackToFront = GL_FALSE;
2047   if (theDrawFbo == theReadFbo
2048    && theDrawFbo != NULL
2049    && theDrawFbo->IsValid())
2050   {
2051     myBackBufferRestored = Standard_False;
2052     theDrawFbo->BindBuffer (aCtx);
2053   }
2054   else if (theReadFbo != NULL
2055         && theReadFbo->IsValid()
2056         && aCtx->IsRender())
2057   {
2058     if (!blitBuffers (theReadFbo, theDrawFbo))
2059     {
2060       return true;
2061     }
2062   }
2063   else if (theDrawFbo == NULL)
2064   {
2065   #if !defined(GL_ES_VERSION_2_0)
2066     aCtx->core11fwd->glGetBooleanv (GL_DOUBLEBUFFER, &toCopyBackToFront);
2067   #endif
2068     if (toCopyBackToFront
2069      && myTransientDrawToFront)
2070     {
2071       if (!HasImmediateStructures()
2072        && !theIsPartialUpdate)
2073       {
2074         // prefer Swap Buffers within Redraw in compatibility mode (without FBO)
2075         return true;
2076       }
2077       if (!copyBackToFront())
2078       {
2079         toCopyBackToFront    = GL_FALSE;
2080         myBackBufferRestored = Standard_False;
2081       }
2082     }
2083     else
2084     {
2085       toCopyBackToFront    = GL_FALSE;
2086       myBackBufferRestored = Standard_False;
2087     }
2088   }
2089   else
2090   {
2091     myBackBufferRestored = Standard_False;
2092   }
2093   myIsImmediateDrawn = Standard_True;
2094
2095   myWorkspace->UseZBuffer()    = Standard_True;
2096   myWorkspace->UseDepthWrite() = Standard_True;
2097   aCtx->core11fwd->glDepthFunc (GL_LEQUAL);
2098   aCtx->core11fwd->glDepthMask (GL_TRUE);
2099   aCtx->core11fwd->glEnable (GL_DEPTH_TEST);
2100   aCtx->core11fwd->glClearDepth (1.0);
2101
2102   render (theProjection, theDrawFbo, theOitAccumFbo, Standard_True);
2103
2104   return !toCopyBackToFront;
2105 }
2106
2107 //=======================================================================
2108 //function : renderShadowMap
2109 //purpose  :
2110 //=======================================================================
2111 void OpenGl_View::renderShadowMap (const Handle(OpenGl_ShadowMap)& theShadowMap)
2112 {
2113   const Handle(OpenGl_Context)& aCtx = myWorkspace->GetGlContext();
2114   if (!theShadowMap->UpdateCamera (*this))
2115   {
2116     return;
2117   }
2118
2119   myBVHSelector.SetViewVolume (theShadowMap->Camera());
2120   myBVHSelector.SetViewportSize (myWindow->Width(), myWindow->Height(), myRenderParams.ResolutionRatio());
2121   myBVHSelector.CacheClipPtsProjections();
2122
2123   myLocalOrigin.SetCoord (0.0, 0.0, 0.0);
2124   aCtx->SetCamera (theShadowMap->Camera());
2125   aCtx->ProjectionState.SetCurrent (theShadowMap->Camera()->ProjectionMatrixF());
2126   aCtx->ApplyProjectionMatrix();
2127
2128   aCtx->ShaderManager()->UpdateMaterialState();
2129   aCtx->ShaderManager()->UpdateModelWorldStateTo (OpenGl_Mat4());
2130   aCtx->ShaderManager()->SetShadingModel (Graphic3d_TypeOfShadingModel_Unlit);
2131
2132   const Handle(OpenGl_FrameBuffer)& aShadowBuffer = theShadowMap->FrameBuffer();
2133   aShadowBuffer->BindBuffer    (aCtx);
2134   aShadowBuffer->SetupViewport (aCtx);
2135
2136   aCtx->SetColorMask (false);
2137   aCtx->SetAllowSampleAlphaToCoverage (false);
2138   aCtx->SetSampleAlphaToCoverage (false);
2139
2140   myWorkspace->UseZBuffer()    = true;
2141   myWorkspace->UseDepthWrite() = true;
2142   aCtx->core11fwd->glDepthFunc (GL_LEQUAL);
2143   aCtx->core11fwd->glDepthMask (GL_TRUE);
2144   aCtx->core11fwd->glEnable (GL_DEPTH_TEST);
2145   aCtx->core11fwd->glClearDepth (1.0);
2146   aCtx->core11fwd->glClear (GL_DEPTH_BUFFER_BIT);
2147
2148   renderScene (Graphic3d_Camera::Projection_Orthographic, aShadowBuffer.get(), NULL, false);
2149
2150   aCtx->SetColorMask (true);
2151   myWorkspace->ResetAppliedAspect();
2152   aCtx->BindProgram (Handle(OpenGl_ShaderProgram)());
2153
2154 //Image_AlienPixMap anImage; anImage.InitZero (Image_Format_Gray, aShadowBuffer->GetVPSizeX(), aShadowBuffer->GetVPSizeY());
2155 //OpenGl_FrameBuffer::BufferDump (aCtx, aShadowBuffer, anImage, Graphic3d_BT_Depth);
2156 //anImage.Save (TCollection_AsciiString ("shadow") + theShadowMap->Texture()->Sampler()->Parameters()->TextureUnit() + ".png");
2157
2158   bindDefaultFbo();
2159 }
2160
2161 //=======================================================================
2162 //function : Render
2163 //purpose  :
2164 //=======================================================================
2165 void OpenGl_View::render (Graphic3d_Camera::Projection theProjection,
2166                           OpenGl_FrameBuffer*          theOutputFBO,
2167                           OpenGl_FrameBuffer*          theOitAccumFbo,
2168                           const Standard_Boolean       theToDrawImmediate)
2169 {
2170   // ==================================
2171   //      Step 1: Prepare for render
2172   // ==================================
2173
2174   const Handle(OpenGl_Context)& aContext = myWorkspace->GetGlContext();
2175   aContext->SetAllowSampleAlphaToCoverage (myRenderParams.ToEnableAlphaToCoverage
2176                                         && theOutputFBO != NULL
2177                                         && theOutputFBO->NbSamples() != 0);
2178
2179 #if !defined(GL_ES_VERSION_2_0)
2180   // Disable current clipping planes
2181   if (aContext->core11ffp != NULL)
2182   {
2183     const Standard_Integer aMaxPlanes = aContext->MaxClipPlanes();
2184     for (Standard_Integer aClipPlaneId = GL_CLIP_PLANE0; aClipPlaneId < GL_CLIP_PLANE0 + aMaxPlanes; ++aClipPlaneId)
2185     {
2186       aContext->core11fwd->glDisable (aClipPlaneId);
2187     }
2188   }
2189 #endif
2190
2191   // update states of OpenGl_BVHTreeSelector (frustum culling algorithm);
2192   // note that we pass here window dimensions ignoring Graphic3d_RenderingParams::RenderResolutionScale
2193   myBVHSelector.SetViewVolume (myCamera);
2194   myBVHSelector.SetViewportSize (myWindow->Width(), myWindow->Height(), myRenderParams.ResolutionRatio());
2195   myBVHSelector.CacheClipPtsProjections();
2196
2197   const Handle(OpenGl_ShaderManager)& aManager = aContext->ShaderManager();
2198   const Handle(Graphic3d_LightSet)&   aLights  = myRenderParams.ShadingModel == Graphic3d_TypeOfShadingModel_Unlit ? myNoShadingLight : myLights;
2199   Standard_Size aLightsRevision = 0;
2200   if (!aLights.IsNull())
2201   {
2202     aLightsRevision = aLights->UpdateRevision();
2203   }
2204   if (StateInfo (myCurrLightSourceState, aManager->LightSourceState().Index()) != myLastLightSourceState
2205    || aLightsRevision != myLightsRevision)
2206   {
2207     myLightsRevision = aLightsRevision;
2208     aManager->UpdateLightSourceStateTo (aLights, SpecIBLMapLevels(), myShadowMaps->IsValid() ? myShadowMaps : Handle(OpenGl_ShadowMapArray)());
2209     myLastLightSourceState = StateInfo (myCurrLightSourceState, aManager->LightSourceState().Index());
2210   }
2211
2212   // Update matrices if camera has changed.
2213   Graphic3d_WorldViewProjState aWVPState = myCamera->WorldViewProjState();
2214   if (myWorldViewProjState != aWVPState)
2215   {
2216     myAccumFrames = 0;
2217     myWorldViewProjState = aWVPState;
2218   }
2219
2220   myLocalOrigin.SetCoord (0.0, 0.0, 0.0);
2221   aContext->SetCamera (myCamera);
2222   if (aManager->ModelWorldState().Index() == 0)
2223   {
2224     aContext->ShaderManager()->UpdateModelWorldStateTo (OpenGl_Mat4());
2225   }
2226
2227   // ====================================
2228   //      Step 2: Redraw background
2229   // ====================================
2230
2231   // Render background
2232   if (!theToDrawImmediate)
2233   {
2234     drawBackground (myWorkspace, theProjection);
2235   }
2236
2237 #if !defined(GL_ES_VERSION_2_0)
2238   // Switch off lighting by default
2239   if (aContext->core11ffp != NULL
2240    && aContext->caps->ffpEnable)
2241   {
2242     aContext->core11fwd->glDisable (GL_LIGHTING);
2243   }
2244 #endif
2245
2246   // =================================
2247   //      Step 3: Redraw main plane
2248   // =================================
2249
2250 #if !defined(GL_ES_VERSION_2_0)
2251   // if the view is scaled normal vectors are scaled to unit
2252   // length for correct displaying of shaded objects
2253   const gp_Pnt anAxialScale = aContext->Camera()->AxialScale();
2254   if (anAxialScale.X() != 1.F ||
2255       anAxialScale.Y() != 1.F ||
2256       anAxialScale.Z() != 1.F)
2257   {
2258     aContext->SetGlNormalizeEnabled (Standard_True);
2259   }
2260   else
2261   {
2262     aContext->SetGlNormalizeEnabled (Standard_False);
2263   }
2264 #endif
2265
2266   aManager->SetShadingModel (OpenGl_ShaderManager::PBRShadingModelFallback (myRenderParams.ShadingModel, checkPBRAvailability()));
2267
2268   // Redraw 3d scene
2269   if (theProjection == Graphic3d_Camera::Projection_MonoLeftEye)
2270   {
2271     aContext->ProjectionState.SetCurrent (aContext->Camera()->ProjectionStereoLeftF());
2272     aContext->ApplyProjectionMatrix();
2273   }
2274   else if (theProjection == Graphic3d_Camera::Projection_MonoRightEye)
2275   {
2276     aContext->ProjectionState.SetCurrent (aContext->Camera()->ProjectionStereoRightF());
2277     aContext->ApplyProjectionMatrix();
2278   }
2279
2280   myWorkspace->SetEnvironmentTexture (myTextureEnv);
2281
2282   const bool hasShadowMap = aContext->ShaderManager()->LightSourceState().HasShadowMaps();
2283   if (hasShadowMap)
2284   {
2285     for (Standard_Integer aShadowIter = myShadowMaps->Lower(); aShadowIter <= myShadowMaps->Upper(); ++aShadowIter)
2286     {
2287       const Handle(OpenGl_ShadowMap)& aShadow = myShadowMaps->Value (aShadowIter);
2288       aShadow->Texture()->Bind (aContext);
2289     }
2290   }
2291
2292   renderScene (theProjection, theOutputFBO, theOitAccumFbo, theToDrawImmediate);
2293
2294   if (hasShadowMap)
2295   {
2296     for (Standard_Integer aShadowIter = myShadowMaps->Lower(); aShadowIter <= myShadowMaps->Upper(); ++aShadowIter)
2297     {
2298       const Handle(OpenGl_ShadowMap)& aShadow = myShadowMaps->Value (aShadowIter);
2299       aShadow->Texture()->Unbind (aContext);
2300     }
2301     if (aContext->core15fwd != NULL)
2302     {
2303       aContext->core15fwd->glActiveTexture (GL_TEXTURE0);
2304     }
2305   }
2306
2307   myWorkspace->SetEnvironmentTexture (Handle(OpenGl_TextureSet)());
2308
2309   // ===============================
2310   //      Step 4: Trihedron
2311   // ===============================
2312
2313   // Resetting GL parameters according to the default aspects
2314   // in order to synchronize GL state with the graphic driver state
2315   // before drawing auxiliary stuff (trihedrons, overlayer)
2316   myWorkspace->ResetAppliedAspect();
2317
2318   // Render trihedron
2319   if (!theToDrawImmediate)
2320   {
2321     renderTrihedron (myWorkspace);
2322   }
2323   else
2324   {
2325     renderFrameStats();
2326   }
2327
2328   myWorkspace->ResetAppliedAspect();
2329   aContext->SetAllowSampleAlphaToCoverage (false);
2330   aContext->SetSampleAlphaToCoverage (false);
2331
2332   // reset FFP state for safety
2333   aContext->BindProgram (Handle(OpenGl_ShaderProgram)());
2334   if (aContext->caps->ffpEnable)
2335   {
2336     aContext->ShaderManager()->PushState (Handle(OpenGl_ShaderProgram)());
2337   }
2338 }
2339
2340 // =======================================================================
2341 // function : InvalidateBVHData
2342 // purpose  :
2343 // =======================================================================
2344 void OpenGl_View::InvalidateBVHData (const Graphic3d_ZLayerId theLayerId)
2345 {
2346   myZLayers.InvalidateBVHData (theLayerId);
2347 }
2348
2349 //=======================================================================
2350 //function : renderStructs
2351 //purpose  :
2352 //=======================================================================
2353 void OpenGl_View::renderStructs (Graphic3d_Camera::Projection theProjection,
2354                                  OpenGl_FrameBuffer*          theReadDrawFbo,
2355                                  OpenGl_FrameBuffer*          theOitAccumFbo,
2356                                  const Standard_Boolean       theToDrawImmediate)
2357 {
2358   myZLayers.UpdateCulling (myWorkspace, theToDrawImmediate);
2359   if ( myZLayers.NbStructures() <= 0 )
2360     return;
2361
2362   Handle(OpenGl_Context) aCtx = myWorkspace->GetGlContext();
2363   Standard_Boolean toRenderGL = theToDrawImmediate ||
2364     myRenderParams.Method != Graphic3d_RM_RAYTRACING ||
2365     myRaytraceInitStatus == OpenGl_RT_FAIL ||
2366     aCtx->IsFeedback();
2367
2368   if (!toRenderGL)
2369   {
2370     const Graphic3d_Vec2i aSizeXY = theReadDrawFbo != NULL
2371                                   ? theReadDrawFbo->GetVPSize()
2372                                   : Graphic3d_Vec2i (myWindow->Width(), myWindow->Height());
2373
2374     toRenderGL = !initRaytraceResources (aSizeXY.x(), aSizeXY.y(), aCtx)
2375               || !updateRaytraceGeometry (OpenGl_GUM_CHECK, myId, aCtx);
2376
2377     toRenderGL |= !myIsRaytraceDataValid; // if no ray-trace data use OpenGL
2378
2379     if (!toRenderGL)
2380     {
2381       myOpenGlFBO ->InitLazy (aCtx, aSizeXY, myFboColorFormat, myFboDepthFormat, 0);
2382       if (theReadDrawFbo != NULL)
2383       {
2384         theReadDrawFbo->UnbindBuffer (aCtx);
2385       }
2386
2387       // Prepare preliminary OpenGL output
2388       if (aCtx->arbFBOBlit != NULL)
2389       {
2390         // Render bottom OSD layer
2391         myZLayers.Render (myWorkspace, theToDrawImmediate, OpenGl_LF_Bottom, theReadDrawFbo, theOitAccumFbo);
2392
2393         const Standard_Integer aPrevFilter = myWorkspace->RenderFilter() & ~(Standard_Integer )(OpenGl_RenderFilter_NonRaytraceableOnly);
2394         myWorkspace->SetRenderFilter (aPrevFilter | OpenGl_RenderFilter_NonRaytraceableOnly);
2395         {
2396           if (theReadDrawFbo != NULL)
2397           {
2398             theReadDrawFbo->BindDrawBuffer (aCtx);
2399           }
2400           else
2401           {
2402             aCtx->arbFBO->glBindFramebuffer (GL_DRAW_FRAMEBUFFER, 0);
2403             aCtx->SetFrameBufferSRGB (false);
2404           }
2405
2406           // Render non-polygonal elements in default layer
2407           myZLayers.Render (myWorkspace, theToDrawImmediate, OpenGl_LF_RayTracable, theReadDrawFbo, theOitAccumFbo);
2408         }
2409         myWorkspace->SetRenderFilter (aPrevFilter);
2410       }
2411
2412       if (theReadDrawFbo != NULL)
2413       {
2414         theReadDrawFbo->BindBuffer (aCtx);
2415       }
2416       else
2417       {
2418         aCtx->arbFBO->glBindFramebuffer (GL_FRAMEBUFFER, 0);
2419         aCtx->SetFrameBufferSRGB (false);
2420       }
2421
2422       // Reset OpenGl aspects state to default to avoid enabling of
2423       // backface culling which is not supported in ray-tracing.
2424       myWorkspace->ResetAppliedAspect();
2425
2426       // Ray-tracing polygonal primitive arrays
2427       raytrace (aSizeXY.x(), aSizeXY.y(), theProjection, theReadDrawFbo, aCtx);
2428
2429       // Render upper (top and topmost) OpenGL layers
2430       myZLayers.Render (myWorkspace, theToDrawImmediate, OpenGl_LF_Upper, theReadDrawFbo, theOitAccumFbo);
2431     }
2432   }
2433
2434   // Redraw 3D scene using OpenGL in standard
2435   // mode or in case of ray-tracing failure
2436   if (toRenderGL)
2437   {
2438     myZLayers.Render (myWorkspace, theToDrawImmediate, OpenGl_LF_All, theReadDrawFbo, theOitAccumFbo);
2439
2440     // Set flag that scene was redrawn by standard pipeline
2441     myWasRedrawnGL = Standard_True;
2442   }
2443 }
2444
2445 //=======================================================================
2446 //function : renderTrihedron
2447 //purpose  :
2448 //=======================================================================
2449 void OpenGl_View::renderTrihedron (const Handle(OpenGl_Workspace) &theWorkspace)
2450 {
2451   if (myToShowGradTrihedron)
2452   {
2453     myGraduatedTrihedron.Render (theWorkspace);
2454   }
2455 }
2456
2457 //=======================================================================
2458 //function : renderFrameStats
2459 //purpose  :
2460 //=======================================================================
2461 void OpenGl_View::renderFrameStats()
2462 {
2463   if (myRenderParams.ToShowStats
2464    && myRenderParams.CollectedStats != Graphic3d_RenderingParams::PerfCounters_NONE)
2465   {
2466     myFrameStatsPrs.Update (myWorkspace);
2467     myFrameStatsPrs.Render (myWorkspace);
2468   }
2469 }
2470
2471 // =======================================================================
2472 // function : Invalidate
2473 // purpose  :
2474 // =======================================================================
2475 void OpenGl_View::Invalidate()
2476 {
2477   myBackBufferRestored = Standard_False;
2478 }
2479
2480 //=======================================================================
2481 //function : renderScene
2482 //purpose  :
2483 //=======================================================================
2484 void OpenGl_View::renderScene (Graphic3d_Camera::Projection theProjection,
2485                                OpenGl_FrameBuffer*          theReadDrawFbo,
2486                                OpenGl_FrameBuffer*          theOitAccumFbo,
2487                                const Standard_Boolean       theToDrawImmediate)
2488 {
2489   const Handle(OpenGl_Context)& aContext = myWorkspace->GetGlContext();
2490
2491   // Specify clipping planes in view transformation space
2492   aContext->ChangeClipping().Reset (myClipPlanes);
2493   if (!myClipPlanes.IsNull()
2494    && !myClipPlanes->IsEmpty())
2495   {
2496     aContext->ShaderManager()->UpdateClippingState();
2497   }
2498
2499   renderStructs (theProjection, theReadDrawFbo, theOitAccumFbo, theToDrawImmediate);
2500   aContext->BindTextures (Handle(OpenGl_TextureSet)(), Handle(OpenGl_ShaderProgram)());
2501
2502   // Apply restored view matrix.
2503   aContext->ApplyWorldViewMatrix();
2504
2505   aContext->ChangeClipping().Reset (Handle(Graphic3d_SequenceOfHClipPlane)());
2506   if (!myClipPlanes.IsNull()
2507    && !myClipPlanes->IsEmpty())
2508   {
2509     aContext->ShaderManager()->RevertClippingState();
2510   }
2511 }
2512
2513 // =======================================================================
2514 // function : bindDefaultFbo
2515 // purpose  :
2516 // =======================================================================
2517 void OpenGl_View::bindDefaultFbo (OpenGl_FrameBuffer* theCustomFbo)
2518 {
2519   Handle(OpenGl_Context) aCtx = myWorkspace->GetGlContext();
2520   OpenGl_FrameBuffer* anFbo = (theCustomFbo != NULL && theCustomFbo->IsValid())
2521                             ?  theCustomFbo
2522                             : (!aCtx->DefaultFrameBuffer().IsNull()
2523                              && aCtx->DefaultFrameBuffer()->IsValid()
2524                               ? aCtx->DefaultFrameBuffer().operator->()
2525                               : NULL);
2526   if (anFbo != NULL)
2527   {
2528     anFbo->BindBuffer (aCtx);
2529     anFbo->SetupViewport (aCtx);
2530   }
2531   else
2532   {
2533   #if !defined(GL_ES_VERSION_2_0)
2534     aCtx->SetReadDrawBuffer (GL_BACK);
2535   #else
2536     if (aCtx->arbFBO != NULL)
2537     {
2538       aCtx->arbFBO->glBindFramebuffer (GL_FRAMEBUFFER, OpenGl_FrameBuffer::NO_FRAMEBUFFER);
2539     }
2540   #endif
2541     const Standard_Integer aViewport[4] = { 0, 0, myWindow->Width(), myWindow->Height() };
2542     aCtx->ResizeViewport (aViewport);
2543   }
2544 }
2545
2546 // =======================================================================
2547 // function : initBlitQuad
2548 // purpose  :
2549 // =======================================================================
2550 OpenGl_VertexBuffer* OpenGl_View::initBlitQuad (const Standard_Boolean theToFlip)
2551 {
2552   OpenGl_VertexBuffer* aVerts = NULL;
2553   if (!theToFlip)
2554   {
2555     aVerts = &myFullScreenQuad;
2556     if (!aVerts->IsValid())
2557     {
2558       OpenGl_Vec4 aQuad[4] =
2559       {
2560         OpenGl_Vec4( 1.0f, -1.0f, 1.0f, 0.0f),
2561         OpenGl_Vec4( 1.0f,  1.0f, 1.0f, 1.0f),
2562         OpenGl_Vec4(-1.0f, -1.0f, 0.0f, 0.0f),
2563         OpenGl_Vec4(-1.0f,  1.0f, 0.0f, 1.0f)
2564       };
2565       aVerts->Init (myWorkspace->GetGlContext(), 4, 4, aQuad[0].GetData());
2566     }
2567   }
2568   else
2569   {
2570     aVerts = &myFullScreenQuadFlip;
2571     if (!aVerts->IsValid())
2572     {
2573       OpenGl_Vec4 aQuad[4] =
2574       {
2575         OpenGl_Vec4( 1.0f, -1.0f, 1.0f, 1.0f),
2576         OpenGl_Vec4( 1.0f,  1.0f, 1.0f, 0.0f),
2577         OpenGl_Vec4(-1.0f, -1.0f, 0.0f, 1.0f),
2578         OpenGl_Vec4(-1.0f,  1.0f, 0.0f, 0.0f)
2579       };
2580       aVerts->Init (myWorkspace->GetGlContext(), 4, 4, aQuad[0].GetData());
2581     }
2582   }
2583   return aVerts;
2584 }
2585
2586 // =======================================================================
2587 // function : blitBuffers
2588 // purpose  :
2589 // =======================================================================
2590 bool OpenGl_View::blitBuffers (OpenGl_FrameBuffer*    theReadFbo,
2591                                OpenGl_FrameBuffer*    theDrawFbo,
2592                                const Standard_Boolean theToFlip)
2593 {
2594   Handle(OpenGl_Context) aCtx = myWorkspace->GetGlContext();
2595   const Standard_Integer aReadSizeX = theReadFbo != NULL ? theReadFbo->GetVPSizeX() : myWindow->Width();
2596   const Standard_Integer aReadSizeY = theReadFbo != NULL ? theReadFbo->GetVPSizeY() : myWindow->Height();
2597   const Standard_Integer aDrawSizeX = theDrawFbo != NULL ? theDrawFbo->GetVPSizeX() : myWindow->Width();
2598   const Standard_Integer aDrawSizeY = theDrawFbo != NULL ? theDrawFbo->GetVPSizeY() : myWindow->Height();
2599   if (theReadFbo == NULL || aCtx->IsFeedback())
2600   {
2601     return false;
2602   }
2603   else if (theReadFbo == theDrawFbo)
2604   {
2605     return true;
2606   }
2607
2608   // clear destination before blitting
2609   if (theDrawFbo != NULL
2610   &&  theDrawFbo->IsValid())
2611   {
2612     theDrawFbo->BindBuffer (aCtx);
2613   }
2614   else
2615   {
2616     aCtx->arbFBO->glBindFramebuffer (GL_FRAMEBUFFER, OpenGl_FrameBuffer::NO_FRAMEBUFFER);
2617     aCtx->SetFrameBufferSRGB (false);
2618   }
2619   const Standard_Integer aViewport[4] = { 0, 0, aDrawSizeX, aDrawSizeY };
2620   aCtx->ResizeViewport (aViewport);
2621
2622   aCtx->SetColorMaskRGBA (NCollection_Vec4<bool> (true)); // force writes into all components, including alpha
2623   aCtx->core20fwd->glClearDepth (1.0);
2624   aCtx->core20fwd->glClearColor (0.0f, 0.0f, 0.0f, aCtx->caps->buffersOpaqueAlpha ? 1.0f : 0.0f);
2625   aCtx->core20fwd->glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
2626   aCtx->SetColorMask (true); // restore default alpha component write state
2627
2628   const bool toApplyGamma = aCtx->ToRenderSRGB() != aCtx->IsFrameBufferSRGB();
2629   if (aCtx->arbFBOBlit != NULL
2630   && !toApplyGamma
2631   &&  theReadFbo->NbSamples() != 0)
2632   {
2633     GLbitfield aCopyMask = 0;
2634     theReadFbo->BindReadBuffer (aCtx);
2635     if (theDrawFbo != NULL
2636      && theDrawFbo->IsValid())
2637     {
2638       theDrawFbo->BindDrawBuffer (aCtx);
2639       if (theDrawFbo->HasColor()
2640        && theReadFbo->HasColor())
2641       {
2642         aCopyMask |= GL_COLOR_BUFFER_BIT;
2643       }
2644       if (theDrawFbo->HasDepth()
2645        && theReadFbo->HasDepth())
2646       {
2647         aCopyMask |= GL_DEPTH_BUFFER_BIT;
2648       }
2649     }
2650     else
2651     {
2652       if (theReadFbo->HasColor())
2653       {
2654         aCopyMask |= GL_COLOR_BUFFER_BIT;
2655       }
2656       if (theReadFbo->HasDepth())
2657       {
2658         aCopyMask |= GL_DEPTH_BUFFER_BIT;
2659       }
2660       aCtx->arbFBO->glBindFramebuffer (GL_DRAW_FRAMEBUFFER, OpenGl_FrameBuffer::NO_FRAMEBUFFER);
2661       aCtx->SetFrameBufferSRGB (false);
2662     }
2663
2664     // we don't copy stencil buffer here... does it matter for performance?
2665     aCtx->arbFBOBlit->glBlitFramebuffer (0, 0, aReadSizeX, aReadSizeY,
2666                                          0, 0, aDrawSizeX, aDrawSizeY,
2667                                          aCopyMask, GL_NEAREST);
2668     const int anErr = aCtx->core11fwd->glGetError();
2669     if (anErr != GL_NO_ERROR)
2670     {
2671       // glBlitFramebuffer() might fail in several cases:
2672       // - Both FBOs have MSAA and they are samples number does not match.
2673       //   OCCT checks that this does not happen,
2674       //   however some graphics drivers provide an option for overriding MSAA.
2675       //   In this case window MSAA might be non-zero (and application can not check it)
2676       //   and might not match MSAA of our offscreen FBOs.
2677       // - Pixel formats of FBOs do not match.
2678       //   This also might happen with window has pixel format,
2679       //   e.g. Mesa fails blitting RGBA8 -> RGB8 while other drivers support this conversion.
2680       TCollection_ExtendedString aMsg = TCollection_ExtendedString() + "FBO blitting has failed [Error " + OpenGl_Context::FormatGlError (anErr) + "]\n"
2681                                       + "  Please check your graphics driver settings or try updating driver.";
2682       if (theReadFbo->NbSamples() != 0)
2683       {
2684         myToDisableMSAA = true;
2685         aMsg += "\n  MSAA settings should not be overridden by driver!";
2686       }
2687       aCtx->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, aMsg);
2688     }
2689
2690     if (theDrawFbo != NULL
2691      && theDrawFbo->IsValid())
2692     {
2693       theDrawFbo->BindBuffer (aCtx);
2694     }
2695     else
2696     {
2697       aCtx->arbFBO->glBindFramebuffer (GL_FRAMEBUFFER, OpenGl_FrameBuffer::NO_FRAMEBUFFER);
2698       aCtx->SetFrameBufferSRGB (false);
2699     }
2700   }
2701   else
2702   {
2703     aCtx->core20fwd->glDepthFunc (GL_ALWAYS);
2704     aCtx->core20fwd->glDepthMask (GL_TRUE);
2705     aCtx->core20fwd->glEnable (GL_DEPTH_TEST);
2706   #if defined(GL_ES_VERSION_2_0)
2707     if (!aCtx->IsGlGreaterEqual (3, 0)
2708      && !aCtx->extFragDepth)
2709     {
2710       aCtx->core20fwd->glDisable (GL_DEPTH_TEST);
2711     }
2712   #endif
2713
2714     aCtx->BindTextures (Handle(OpenGl_TextureSet)(), Handle(OpenGl_ShaderProgram)());
2715
2716     const Graphic3d_TypeOfTextureFilter aFilter = (aDrawSizeX == aReadSizeX && aDrawSizeY == aReadSizeY) ? Graphic3d_TOTF_NEAREST : Graphic3d_TOTF_BILINEAR;
2717     const GLint aFilterGl = aFilter == Graphic3d_TOTF_NEAREST ? GL_NEAREST : GL_LINEAR;
2718
2719     OpenGl_VertexBuffer* aVerts = initBlitQuad (theToFlip);
2720     const Handle(OpenGl_ShaderManager)& aManager = aCtx->ShaderManager();
2721     if (aVerts->IsValid()
2722      && aManager->BindFboBlitProgram (theReadFbo != NULL ? theReadFbo->NbSamples() : 0, toApplyGamma))
2723     {
2724       aCtx->SetSampleAlphaToCoverage (false);
2725       theReadFbo->ColorTexture()->Bind (aCtx, Graphic3d_TextureUnit_0);
2726       if (theReadFbo->ColorTexture()->Sampler()->Parameters()->Filter() != aFilter)
2727       {
2728         theReadFbo->ColorTexture()->Sampler()->Parameters()->SetFilter (aFilter);
2729         aCtx->core20fwd->glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, aFilterGl);
2730         aCtx->core20fwd->glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, aFilterGl);
2731       }
2732
2733       theReadFbo->DepthStencilTexture()->Bind (aCtx, Graphic3d_TextureUnit_1);
2734       if (theReadFbo->DepthStencilTexture()->Sampler()->Parameters()->Filter() != aFilter)
2735       {
2736         theReadFbo->DepthStencilTexture()->Sampler()->Parameters()->SetFilter (aFilter);
2737         aCtx->core20fwd->glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, aFilterGl);
2738         aCtx->core20fwd->glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, aFilterGl);
2739       }
2740
2741       aVerts->BindVertexAttrib (aCtx, Graphic3d_TOA_POS);
2742
2743       aCtx->core20fwd->glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2744
2745       aVerts->UnbindVertexAttrib (aCtx, Graphic3d_TOA_POS);
2746       theReadFbo->DepthStencilTexture()->Unbind (aCtx, Graphic3d_TextureUnit_1);
2747       theReadFbo->ColorTexture()       ->Unbind (aCtx, Graphic3d_TextureUnit_0);
2748       aCtx->BindProgram (NULL);
2749     }
2750     else
2751     {
2752       TCollection_ExtendedString aMsg = TCollection_ExtendedString()
2753         + "Error! FBO blitting has failed";
2754       aCtx->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
2755                          GL_DEBUG_TYPE_ERROR,
2756                          0,
2757                          GL_DEBUG_SEVERITY_HIGH,
2758                          aMsg);
2759       myHasFboBlit = Standard_False;
2760       theReadFbo->Release (aCtx.operator->());
2761       return true;
2762     }
2763   }
2764   return true;
2765 }
2766
2767 // =======================================================================
2768 // function : drawStereoPair
2769 // purpose  :
2770 // =======================================================================
2771 void OpenGl_View::drawStereoPair (OpenGl_FrameBuffer* theDrawFbo)
2772 {
2773   const Handle(OpenGl_Context)& aCtx = myWorkspace->GetGlContext();
2774   bindDefaultFbo (theDrawFbo);
2775   OpenGl_FrameBuffer* aPair[2] =
2776   {
2777     myImmediateSceneFbos[0]->IsValid() ? myImmediateSceneFbos[0].operator->() : NULL,
2778     myImmediateSceneFbos[1]->IsValid() ? myImmediateSceneFbos[1].operator->() : NULL
2779   };
2780   if (aPair[0] == NULL
2781   ||  aPair[1] == NULL
2782   || !myTransientDrawToFront)
2783   {
2784     aPair[0] = myMainSceneFbos[0]->IsValid() ? myMainSceneFbos[0].operator->() : NULL;
2785     aPair[1] = myMainSceneFbos[1]->IsValid() ? myMainSceneFbos[1].operator->() : NULL;
2786   }
2787
2788   if (aPair[0] == NULL
2789    || aPair[1] == NULL)
2790   {
2791     return;
2792   }
2793
2794   if (aPair[0]->NbSamples() != 0)
2795   {
2796     // resolve MSAA buffers before drawing
2797     if (!myOpenGlFBO ->InitLazy (aCtx, aPair[0]->GetVPSize(), myFboColorFormat, myFboDepthFormat, 0)
2798      || !myOpenGlFBO2->InitLazy (aCtx, aPair[0]->GetVPSize(), myFboColorFormat, 0, 0))
2799     {
2800       aCtx->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
2801                          GL_DEBUG_TYPE_ERROR,
2802                          0,
2803                          GL_DEBUG_SEVERITY_HIGH,
2804                          "Error! Unable to allocate FBO for blitting stereo pair");
2805       bindDefaultFbo (theDrawFbo);
2806       return;
2807     }
2808
2809     if (!blitBuffers (aPair[0], myOpenGlFBO .operator->(), Standard_False)
2810      || !blitBuffers (aPair[1], myOpenGlFBO2.operator->(), Standard_False))
2811     {
2812       bindDefaultFbo (theDrawFbo);
2813       return;
2814     }
2815
2816     aPair[0] = myOpenGlFBO .operator->();
2817     aPair[1] = myOpenGlFBO2.operator->();
2818     bindDefaultFbo (theDrawFbo);
2819   }
2820
2821   struct
2822   {
2823     Standard_Integer left;
2824     Standard_Integer top;
2825     Standard_Integer right;
2826     Standard_Integer bottom;
2827     Standard_Integer dx() { return right  - left; }
2828     Standard_Integer dy() { return bottom - top; }
2829   } aGeom;
2830
2831   myWindow->PlatformWindow()->Position (aGeom.left, aGeom.top, aGeom.right, aGeom.bottom);
2832
2833   Standard_Boolean toReverse = myRenderParams.ToReverseStereo;
2834   const Standard_Boolean isOddY = (aGeom.top + aGeom.dy()) % 2 == 1;
2835   const Standard_Boolean isOddX =  aGeom.left % 2 == 1;
2836   if (isOddY
2837    && (myRenderParams.StereoMode == Graphic3d_StereoMode_RowInterlaced
2838     || myRenderParams.StereoMode == Graphic3d_StereoMode_ChessBoard))
2839   {
2840     toReverse = !toReverse;
2841   }
2842   if (isOddX
2843    && (myRenderParams.StereoMode == Graphic3d_StereoMode_ColumnInterlaced
2844     || myRenderParams.StereoMode == Graphic3d_StereoMode_ChessBoard))
2845   {
2846     toReverse = !toReverse;
2847   }
2848
2849   if (toReverse)
2850   {
2851     std::swap (aPair[0], aPair[1]);
2852   }
2853
2854   aCtx->core20fwd->glDepthFunc (GL_ALWAYS);
2855   aCtx->core20fwd->glDepthMask (GL_TRUE);
2856   aCtx->core20fwd->glEnable (GL_DEPTH_TEST);
2857
2858   aCtx->BindTextures (Handle(OpenGl_TextureSet)(), Handle(OpenGl_ShaderProgram)());
2859   OpenGl_VertexBuffer* aVerts = initBlitQuad (myToFlipOutput);
2860
2861   const Handle(OpenGl_ShaderManager)& aManager = aCtx->ShaderManager();
2862   if (aVerts->IsValid()
2863    && aManager->BindStereoProgram (myRenderParams.StereoMode))
2864   {
2865     if (myRenderParams.StereoMode == Graphic3d_StereoMode_Anaglyph)
2866     {
2867       OpenGl_Mat4 aFilterL, aFilterR;
2868       aFilterL.SetDiagonal (Graphic3d_Vec4 (0.0f, 0.0f, 0.0f, 0.0f));
2869       aFilterR.SetDiagonal (Graphic3d_Vec4 (0.0f, 0.0f, 0.0f, 0.0f));
2870       switch (myRenderParams.AnaglyphFilter)
2871       {
2872         case Graphic3d_RenderingParams::Anaglyph_RedCyan_Simple:
2873         {
2874           aFilterL.SetRow (0, Graphic3d_Vec4 (1.0f, 0.0f, 0.0f, 0.0f));
2875           aFilterR.SetRow (1, Graphic3d_Vec4 (0.0f, 1.0f, 0.0f, 0.0f));
2876           aFilterR.SetRow (2, Graphic3d_Vec4 (0.0f, 0.0f, 1.0f, 0.0f));
2877           break;
2878         }
2879         case Graphic3d_RenderingParams::Anaglyph_RedCyan_Optimized:
2880         {
2881           aFilterL.SetRow (0, Graphic3d_Vec4 ( 0.4154f,      0.4710f,      0.16666667f, 0.0f));
2882           aFilterL.SetRow (1, Graphic3d_Vec4 (-0.0458f,     -0.0484f,     -0.0257f,     0.0f));
2883           aFilterL.SetRow (2, Graphic3d_Vec4 (-0.0547f,     -0.0615f,      0.0128f,     0.0f));
2884           aFilterL.SetRow (3, Graphic3d_Vec4 ( 0.0f,         0.0f,         0.0f,        0.0f));
2885           aFilterR.SetRow (0, Graphic3d_Vec4 (-0.01090909f, -0.03636364f, -0.00606061f, 0.0f));
2886           aFilterR.SetRow (1, Graphic3d_Vec4 ( 0.37560000f,  0.73333333f,  0.01111111f, 0.0f));
2887           aFilterR.SetRow (2, Graphic3d_Vec4 (-0.06510000f, -0.12870000f,  1.29710000f, 0.0f));
2888           aFilterR.SetRow (3, Graphic3d_Vec4 ( 0.0f,                0.0f,  0.0f,        0.0f));
2889           break;
2890         }
2891         case Graphic3d_RenderingParams::Anaglyph_YellowBlue_Simple:
2892         {
2893           aFilterL.SetRow (0, Graphic3d_Vec4 (1.0f, 0.0f, 0.0f, 0.0f));
2894           aFilterL.SetRow (1, Graphic3d_Vec4 (0.0f, 1.0f, 0.0f, 0.0f));
2895           aFilterR.SetRow (2, Graphic3d_Vec4 (0.0f, 0.0f, 1.0f, 0.0f));
2896           break;
2897         }
2898         case Graphic3d_RenderingParams::Anaglyph_YellowBlue_Optimized:
2899         {
2900           aFilterL.SetRow (0, Graphic3d_Vec4 ( 1.062f, -0.205f,  0.299f, 0.0f));
2901           aFilterL.SetRow (1, Graphic3d_Vec4 (-0.026f,  0.908f,  0.068f, 0.0f));
2902           aFilterL.SetRow (2, Graphic3d_Vec4 (-0.038f, -0.173f,  0.022f, 0.0f));
2903           aFilterL.SetRow (3, Graphic3d_Vec4 ( 0.0f,    0.0f,    0.0f,   0.0f));
2904           aFilterR.SetRow (0, Graphic3d_Vec4 (-0.016f, -0.123f, -0.017f, 0.0f));
2905           aFilterR.SetRow (1, Graphic3d_Vec4 ( 0.006f,  0.062f, -0.017f, 0.0f));
2906           aFilterR.SetRow (2, Graphic3d_Vec4 ( 0.094f,  0.185f,  0.911f, 0.0f));
2907           aFilterR.SetRow (3, Graphic3d_Vec4 ( 0.0f,    0.0f,    0.0f,   0.0f));
2908           break;
2909         }
2910         case Graphic3d_RenderingParams::Anaglyph_GreenMagenta_Simple:
2911         {
2912           aFilterR.SetRow (0, Graphic3d_Vec4 (1.0f, 0.0f, 0.0f, 0.0f));
2913           aFilterL.SetRow (1, Graphic3d_Vec4 (0.0f, 1.0f, 0.0f, 0.0f));
2914           aFilterR.SetRow (2, Graphic3d_Vec4 (0.0f, 0.0f, 1.0f, 0.0f));
2915           break;
2916         }
2917         case Graphic3d_RenderingParams::Anaglyph_UserDefined:
2918         {
2919           aFilterL = myRenderParams.AnaglyphLeft;
2920           aFilterR = myRenderParams.AnaglyphRight;
2921           break;
2922         }
2923       }
2924       aCtx->ActiveProgram()->SetUniform (aCtx, "uMultL", aFilterL);
2925       aCtx->ActiveProgram()->SetUniform (aCtx, "uMultR", aFilterR);
2926     }
2927
2928     aPair[0]->ColorTexture()->Bind (aCtx, Graphic3d_TextureUnit_0);
2929     aPair[1]->ColorTexture()->Bind (aCtx, Graphic3d_TextureUnit_1);
2930     aVerts->BindVertexAttrib (aCtx, 0);
2931
2932     aCtx->core20fwd->glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
2933
2934     aVerts->UnbindVertexAttrib (aCtx, 0);
2935     aPair[1]->ColorTexture()->Unbind (aCtx, Graphic3d_TextureUnit_1);
2936     aPair[0]->ColorTexture()->Unbind (aCtx, Graphic3d_TextureUnit_0);
2937   }
2938   else
2939   {
2940     TCollection_ExtendedString aMsg = TCollection_ExtendedString()
2941       + "Error! Anaglyph has failed";
2942     aCtx->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
2943                        GL_DEBUG_TYPE_ERROR,
2944                        0,
2945                        GL_DEBUG_SEVERITY_HIGH,
2946                        aMsg);
2947   }
2948 }
2949
2950 // =======================================================================
2951 // function : copyBackToFront
2952 // purpose  :
2953 // =======================================================================
2954 bool OpenGl_View::copyBackToFront()
2955 {
2956   myIsImmediateDrawn = Standard_False;
2957 #if !defined(GL_ES_VERSION_2_0)
2958   const Handle(OpenGl_Context)& aCtx = myWorkspace->GetGlContext();
2959   if (aCtx->core11ffp == NULL)
2960   {
2961     return false;
2962   }
2963
2964   OpenGl_Mat4 aProjectMat;
2965   Graphic3d_TransformUtils::Ortho2D (aProjectMat,
2966                                      0.0f, static_cast<GLfloat> (myWindow->Width()),
2967                                      0.0f, static_cast<GLfloat> (myWindow->Height()));
2968
2969   aCtx->WorldViewState.Push();
2970   aCtx->ProjectionState.Push();
2971
2972   aCtx->WorldViewState.SetIdentity();
2973   aCtx->ProjectionState.SetCurrent (aProjectMat);
2974
2975   aCtx->ApplyProjectionMatrix();
2976   aCtx->ApplyWorldViewMatrix();
2977
2978   // synchronize FFP state before copying pixels
2979   aCtx->BindProgram (Handle(OpenGl_ShaderProgram)());
2980   aCtx->ShaderManager()->PushState (Handle(OpenGl_ShaderProgram)());
2981   aCtx->DisableFeatures();
2982
2983   switch (aCtx->DrawBuffer())
2984   {
2985     case GL_BACK_LEFT:
2986     {
2987       aCtx->SetReadBuffer (GL_BACK_LEFT);
2988       aCtx->SetDrawBuffer (GL_FRONT_LEFT);
2989       break;
2990     }
2991     case GL_BACK_RIGHT:
2992     {
2993       aCtx->SetReadBuffer (GL_BACK_RIGHT);
2994       aCtx->SetDrawBuffer (GL_FRONT_RIGHT);
2995       break;
2996     }
2997     default:
2998     {
2999       aCtx->SetReadBuffer (GL_BACK);
3000       aCtx->SetDrawBuffer (GL_FRONT);
3001       break;
3002     }
3003   }
3004
3005   aCtx->core11ffp->glRasterPos2i (0, 0);
3006   aCtx->core11ffp->glCopyPixels  (0, 0, myWindow->Width() + 1, myWindow->Height() + 1, GL_COLOR);
3007   //aCtx->core11ffp->glCopyPixels  (0, 0, myWidth + 1, myHeight + 1, GL_DEPTH);
3008
3009   aCtx->EnableFeatures();
3010
3011   aCtx->WorldViewState.Pop();
3012   aCtx->ProjectionState.Pop();
3013   aCtx->ApplyProjectionMatrix();
3014
3015   // read/write from front buffer now
3016   aCtx->SetReadBuffer (aCtx->DrawBuffer());
3017   return true;
3018 #else
3019   return false;
3020 #endif
3021 }
3022
3023 // =======================================================================
3024 // function : checkOitCompatibility
3025 // purpose  :
3026 // =======================================================================
3027 Standard_Boolean OpenGl_View::checkOitCompatibility (const Handle(OpenGl_Context)& theGlContext,
3028                                                      const Standard_Boolean theMSAA)
3029 {
3030   // determine if OIT is supported by current OpenGl context
3031   Standard_Boolean& aToDisableOIT = theMSAA ? myToDisableMSAA : myToDisableOIT;
3032   if (aToDisableOIT)
3033   {
3034     return Standard_False;
3035   }
3036
3037   TCollection_ExtendedString aCompatibilityMsg;
3038   if (theGlContext->hasFloatBuffer     == OpenGl_FeatureNotAvailable
3039    && theGlContext->hasHalfFloatBuffer == OpenGl_FeatureNotAvailable)
3040   {
3041     aCompatibilityMsg += "OpenGL context does not support floating-point RGBA color buffer format.\n";
3042   }
3043   if (theMSAA && theGlContext->hasSampleVariables == OpenGl_FeatureNotAvailable)
3044   {
3045     aCompatibilityMsg += "Current version of GLSL does not support built-in sample variables.\n";
3046   }
3047   if (theGlContext->hasDrawBuffers == OpenGl_FeatureNotAvailable)
3048   {
3049     aCompatibilityMsg += "OpenGL context does not support multiple draw buffers.\n";
3050   }
3051   if (aCompatibilityMsg.IsEmpty())
3052   {
3053     return Standard_True;
3054   }
3055
3056   aCompatibilityMsg += "  Blended order-independent transparency will not be available.\n";
3057   theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
3058                           GL_DEBUG_TYPE_ERROR,
3059                           0,
3060                           GL_DEBUG_SEVERITY_HIGH,
3061                           aCompatibilityMsg);
3062
3063   aToDisableOIT = Standard_True;
3064   return Standard_False;
3065 }
3066
3067 // =======================================================================
3068 // function : checkPBRAvailability
3069 // purpose  :
3070 // =======================================================================
3071 Standard_Boolean OpenGl_View::checkPBRAvailability() const
3072 {
3073   return myWorkspace->GetGlContext()->HasPBR()
3074       && !myPBREnvironment.IsNull();
3075 }
3076
3077 // =======================================================================
3078 // function : updatePBREnvironment
3079 // purpose  :
3080 // =======================================================================
3081 void OpenGl_View::updatePBREnvironment (const Handle(OpenGl_Context)& theCtx)
3082 {
3083   if (myPBREnvState != OpenGl_PBREnvState_CREATED
3084   || !myPBREnvRequest)
3085   {
3086     myPBREnvRequest = false;
3087     return;
3088   }
3089
3090   myPBREnvRequest = false;
3091
3092   Handle(OpenGl_TextureSet) aGlTextureSet;
3093   OpenGl_Aspects* aTmpGlAspects = NULL;
3094   if (!myCubeMapIBL.IsNull()
3095     && myCubeMapIBL == myCubeMapBackground)
3096   {
3097     aGlTextureSet = myCubeMapParams->TextureSet (theCtx);
3098   }
3099   else if (!myCubeMapIBL.IsNull())
3100   {
3101     myCubeMapIBL->SetMipmapsGeneration (Standard_True);
3102
3103     Handle(Graphic3d_AspectFillArea3d) anAspect = new Graphic3d_AspectFillArea3d();
3104     {
3105       Handle(Graphic3d_TextureSet) aTextureSet = new Graphic3d_TextureSet (myCubeMapIBL);
3106       anAspect->SetInteriorStyle (Aspect_IS_SOLID);
3107       anAspect->SetTextureSet (aTextureSet);
3108       anAspect->SetTextureMapOn (true);
3109     }
3110
3111     aTmpGlAspects = new OpenGl_Aspects();
3112     aTmpGlAspects->SetAspect (anAspect);
3113     aGlTextureSet = aTmpGlAspects->TextureSet (theCtx);
3114   }
3115
3116   if (!aGlTextureSet.IsNull()
3117    && !aGlTextureSet->IsEmpty())
3118   {
3119     myPBREnvironment->Bake (theCtx,
3120                             aGlTextureSet->First(),
3121                             myCubeMapIBL->ZIsInverted(),
3122                             myCubeMapIBL->IsTopDown(),
3123                             myRenderParams.PbrEnvBakingDiffNbSamples,
3124                             myRenderParams.PbrEnvBakingSpecNbSamples,
3125                             myRenderParams.PbrEnvBakingProbability);
3126   }
3127   else
3128   {
3129     myPBREnvironment->Clear (theCtx);
3130   }
3131   aGlTextureSet.Nullify();
3132   OpenGl_Element::Destroy (theCtx.get(), aTmpGlAspects);
3133 }