0029516: Visualization - eliminate redundant property Graphic3d_MaterialAspect::Refle...
[occt.git] / src / OpenGl / OpenGl_View_Raytrace.cxx
1 // Created on: 2015-02-20
2 // Created by: Denis BOGOLEPOV
3 // Copyright (c) 2015 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 <Graphic3d_TextureParams.hxx>
19 #include <OpenGl_PrimitiveArray.hxx>
20 #include <OpenGl_VertexBuffer.hxx>
21 #include <OpenGl_GlCore44.hxx>
22 #include <OSD_Protection.hxx>
23 #include <OSD_File.hxx>
24
25 #include "../Shaders/Shaders_RaytraceBase_vs.pxx"
26 #include "../Shaders/Shaders_RaytraceBase_fs.pxx"
27 #include "../Shaders/Shaders_PathtraceBase_fs.pxx"
28 #include "../Shaders/Shaders_RaytraceRender_fs.pxx"
29 #include "../Shaders/Shaders_RaytraceSmooth_fs.pxx"
30 #include "../Shaders/Shaders_Display_fs.pxx"
31
32 //! Use this macro to output ray-tracing debug info
33 // #define RAY_TRACE_PRINT_INFO
34
35 #ifdef RAY_TRACE_PRINT_INFO
36   #include <OSD_Timer.hxx>
37 #endif
38
39 namespace
40 {
41   static const OpenGl_Vec4 THE_WHITE_COLOR (1.0f, 1.0f, 1.0f, 1.0f);
42   static const OpenGl_Vec4 THE_BLACK_COLOR (0.0f, 0.0f, 0.0f, 1.0f);
43 }
44
45 namespace
46 {
47   //! Defines OpenGL texture samplers.
48   static const Graphic3d_TextureUnit OpenGl_RT_EnvironmentMapTexture = Graphic3d_TextureUnit_0;
49
50   static const Graphic3d_TextureUnit OpenGl_RT_SceneNodeInfoTexture  = Graphic3d_TextureUnit_1;
51   static const Graphic3d_TextureUnit OpenGl_RT_SceneMinPointTexture  = Graphic3d_TextureUnit_2;
52   static const Graphic3d_TextureUnit OpenGl_RT_SceneMaxPointTexture  = Graphic3d_TextureUnit_3;
53   static const Graphic3d_TextureUnit OpenGl_RT_SceneTransformTexture = Graphic3d_TextureUnit_4;
54
55   static const Graphic3d_TextureUnit OpenGl_RT_GeometryVertexTexture = Graphic3d_TextureUnit_5;
56   static const Graphic3d_TextureUnit OpenGl_RT_GeometryNormalTexture = Graphic3d_TextureUnit_6;
57   static const Graphic3d_TextureUnit OpenGl_RT_GeometryTexCrdTexture = Graphic3d_TextureUnit_7;
58   static const Graphic3d_TextureUnit OpenGl_RT_GeometryTriangTexture = Graphic3d_TextureUnit_8;
59
60   static const Graphic3d_TextureUnit OpenGl_RT_RaytraceMaterialTexture = Graphic3d_TextureUnit_9;
61   static const Graphic3d_TextureUnit OpenGl_RT_RaytraceLightSrcTexture = Graphic3d_TextureUnit_10;
62
63   static const Graphic3d_TextureUnit OpenGl_RT_FsaaInputTexture = Graphic3d_TextureUnit_11;
64   static const Graphic3d_TextureUnit OpenGl_RT_PrevAccumTexture = Graphic3d_TextureUnit_12;
65
66   static const Graphic3d_TextureUnit OpenGl_RT_RaytraceDepthTexture = Graphic3d_TextureUnit_13;
67 }
68
69 // =======================================================================
70 // function : updateRaytraceGeometry
71 // purpose  : Updates 3D scene geometry for ray-tracing
72 // =======================================================================
73 Standard_Boolean OpenGl_View::updateRaytraceGeometry (const RaytraceUpdateMode      theMode,
74                                                       const Standard_Integer        theViewId,
75                                                       const Handle(OpenGl_Context)& theGlContext)
76 {
77   // In 'check' mode (OpenGl_GUM_CHECK) the scene geometry is analyzed for
78   // modifications. This is light-weight procedure performed on each frame
79   if (theMode == OpenGl_GUM_CHECK)
80   {
81     if (myRaytraceLayerListState != myZLayers.ModificationStateOfRaytracable())
82     {
83       return updateRaytraceGeometry (OpenGl_GUM_PREPARE, theViewId, theGlContext);
84     }
85   }
86   else if (theMode == OpenGl_GUM_PREPARE)
87   {
88     myRaytraceGeometry.ClearMaterials();
89
90     myArrayToTrianglesMap.clear();
91
92     myIsRaytraceDataValid = Standard_False;
93   }
94
95   // The set of processed structures (reflected to ray-tracing)
96   // This set is used to remove out-of-date records from the
97   // hash map of structures
98   std::set<const OpenGl_Structure*> anElements;
99
100   // Set to store all currently visible OpenGL primitive arrays
101   // applicable for ray-tracing
102   std::set<Standard_Size> anArrayIDs;
103
104   // Set to store all non-raytracable elements allowing tracking
105   // of changes in OpenGL scene (only for path tracing)
106   std::set<Standard_Integer> aNonRaytraceIDs;
107
108   for (NCollection_List<Handle(Graphic3d_Layer)>::Iterator aLayerIter (myZLayers.Layers()); aLayerIter.More(); aLayerIter.Next())
109   {
110     const Handle(OpenGl_Layer)& aLayer = aLayerIter.Value();
111     if (aLayer->NbStructures() == 0
112     || !aLayer->LayerSettings().IsRaytracable()
113     ||  aLayer->LayerSettings().IsImmediate())
114     {
115       continue;
116     }
117
118     const Graphic3d_ArrayOfIndexedMapOfStructure& aStructArray = aLayer->ArrayOfStructures();
119     for (Standard_Integer anIndex = 0; anIndex < aStructArray.Length(); ++anIndex)
120     {
121       for (OpenGl_Structure::StructIterator aStructIt (aStructArray.Value (anIndex)); aStructIt.More(); aStructIt.Next())
122       {
123         const OpenGl_Structure* aStructure = aStructIt.Value();
124
125         if (theMode == OpenGl_GUM_CHECK)
126         {
127           if (toUpdateStructure (aStructure))
128           {
129             return updateRaytraceGeometry (OpenGl_GUM_PREPARE, theViewId, theGlContext);
130           }
131           else if (aStructure->IsVisible() && myRaytraceParameters.GlobalIllumination)
132           {
133             aNonRaytraceIDs.insert (aStructure->highlight ? aStructure->Id : -aStructure->Id);
134           }
135         }
136         else if (theMode == OpenGl_GUM_PREPARE)
137         {
138           if (!aStructure->IsRaytracable() || !aStructure->IsVisible())
139           {
140             continue;
141           }
142           else if (!aStructure->ViewAffinity.IsNull() && !aStructure->ViewAffinity->IsVisible (theViewId))
143           {
144             continue;
145           }
146
147           for (OpenGl_Structure::GroupIterator aGroupIter (aStructure->Groups()); aGroupIter.More(); aGroupIter.Next())
148           {
149             // Extract OpenGL elements from the group (primitives arrays)
150             for (const OpenGl_ElementNode* aNode = aGroupIter.Value()->FirstNode(); aNode != NULL; aNode = aNode->next)
151             {
152               OpenGl_PrimitiveArray* aPrimArray = dynamic_cast<OpenGl_PrimitiveArray*> (aNode->elem);
153
154               if (aPrimArray != NULL)
155               {
156                 anArrayIDs.insert (aPrimArray->GetUID());
157               }
158             }
159           }
160         }
161         else if (theMode == OpenGl_GUM_REBUILD)
162         {
163           if (!aStructure->IsRaytracable())
164           {
165             continue;
166           }
167           else if (addRaytraceStructure (aStructure, theGlContext))
168           {
169             anElements.insert (aStructure); // structure was processed
170           }
171         }
172       }
173     }
174   }
175
176   if (theMode == OpenGl_GUM_PREPARE)
177   {
178     BVH_ObjectSet<Standard_ShortReal, 3>::BVH_ObjectList anUnchangedObjects;
179
180     // Filter out unchanged objects so only their transformations and materials
181     // will be updated (and newly added objects will be processed from scratch)
182     for (Standard_Integer anObjIdx = 0; anObjIdx < myRaytraceGeometry.Size(); ++anObjIdx)
183     {
184       OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
185         myRaytraceGeometry.Objects().ChangeValue (anObjIdx).operator->());
186
187       if (aTriangleSet == NULL)
188       {
189         continue;
190       }
191
192       if (anArrayIDs.find (aTriangleSet->AssociatedPArrayID()) != anArrayIDs.end())
193       {
194         anUnchangedObjects.Append (myRaytraceGeometry.Objects().Value (anObjIdx));
195
196         myArrayToTrianglesMap[aTriangleSet->AssociatedPArrayID()] = aTriangleSet;
197       }
198     }
199
200     myRaytraceGeometry.Objects() = anUnchangedObjects;
201
202     return updateRaytraceGeometry (OpenGl_GUM_REBUILD, theViewId, theGlContext);
203   }
204   else if (theMode == OpenGl_GUM_REBUILD)
205   {
206     // Actualize the hash map of structures - remove out-of-date records
207     std::map<const OpenGl_Structure*, StructState>::iterator anIter = myStructureStates.begin();
208
209     while (anIter != myStructureStates.end())
210     {
211       if (anElements.find (anIter->first) == anElements.end())
212       {
213         myStructureStates.erase (anIter++);
214       }
215       else
216       {
217         ++anIter;
218       }
219     }
220
221     // Actualize OpenGL layer list state
222     myRaytraceLayerListState = myZLayers.ModificationStateOfRaytracable();
223
224     // Rebuild two-level acceleration structure
225     myRaytraceGeometry.ProcessAcceleration();
226
227     myRaytraceSceneRadius = 2.f /* scale factor */ * std::max (
228       myRaytraceGeometry.Box().CornerMin().cwiseAbs().maxComp(),
229       myRaytraceGeometry.Box().CornerMax().cwiseAbs().maxComp());
230
231     const BVH_Vec3f aSize = myRaytraceGeometry.Box().Size();
232
233     myRaytraceSceneEpsilon = Max (1.0e-6f, 1.0e-4f * aSize.Modulus());
234
235     return uploadRaytraceData (theGlContext);
236   }
237
238   if (myRaytraceParameters.GlobalIllumination)
239   {
240     Standard_Boolean toRestart =
241       aNonRaytraceIDs.size() != myNonRaytraceStructureIDs.size();
242
243     for (std::set<Standard_Integer>::iterator anID = aNonRaytraceIDs.begin(); anID != aNonRaytraceIDs.end() && !toRestart; ++anID)
244     {
245       if (myNonRaytraceStructureIDs.find (*anID) == myNonRaytraceStructureIDs.end())
246       {
247         toRestart = Standard_True;
248       }
249     }
250
251     if (toRestart)
252     {
253       myAccumFrames = 0;
254     }
255
256     myNonRaytraceStructureIDs = aNonRaytraceIDs;
257   }
258
259   return Standard_True;
260 }
261
262 // =======================================================================
263 // function : toUpdateStructure
264 // purpose  : Checks to see if the structure is modified
265 // =======================================================================
266 Standard_Boolean OpenGl_View::toUpdateStructure (const OpenGl_Structure* theStructure)
267 {
268   if (!theStructure->IsRaytracable())
269   {
270     if (theStructure->ModificationState() > 0)
271     {
272       theStructure->ResetModificationState();
273
274       return Standard_True; // ray-trace element was removed - need to rebuild
275     }
276
277     return Standard_False; // did not contain ray-trace elements
278   }
279
280   std::map<const OpenGl_Structure*, StructState>::iterator aStructState = myStructureStates.find (theStructure);
281
282   if (aStructState == myStructureStates.end() || aStructState->second.StructureState != theStructure->ModificationState())
283   {
284     return Standard_True;
285   }
286   else if (theStructure->InstancedStructure() != NULL)
287   {
288     return aStructState->second.InstancedState != theStructure->InstancedStructure()->ModificationState();
289   }
290
291   return Standard_False;
292 }
293
294 // =======================================================================
295 // function : buildTextureTransform
296 // purpose  : Constructs texture transformation matrix
297 // =======================================================================
298 void buildTextureTransform (const Handle(Graphic3d_TextureParams)& theParams, BVH_Mat4f& theMatrix)
299 {
300   theMatrix.InitIdentity();
301   if (theParams.IsNull())
302   {
303     return;
304   }
305
306   // Apply scaling
307   const Graphic3d_Vec2& aScale = theParams->Scale();
308
309   theMatrix.ChangeValue (0, 0) *= aScale.x();
310   theMatrix.ChangeValue (1, 0) *= aScale.x();
311   theMatrix.ChangeValue (2, 0) *= aScale.x();
312   theMatrix.ChangeValue (3, 0) *= aScale.x();
313
314   theMatrix.ChangeValue (0, 1) *= aScale.y();
315   theMatrix.ChangeValue (1, 1) *= aScale.y();
316   theMatrix.ChangeValue (2, 1) *= aScale.y();
317   theMatrix.ChangeValue (3, 1) *= aScale.y();
318
319   // Apply translation
320   const Graphic3d_Vec2 aTrans = -theParams->Translation();
321
322   theMatrix.ChangeValue (0, 3) = theMatrix.GetValue (0, 0) * aTrans.x() +
323                                  theMatrix.GetValue (0, 1) * aTrans.y();
324
325   theMatrix.ChangeValue (1, 3) = theMatrix.GetValue (1, 0) * aTrans.x() +
326                                  theMatrix.GetValue (1, 1) * aTrans.y();
327
328   theMatrix.ChangeValue (2, 3) = theMatrix.GetValue (2, 0) * aTrans.x() +
329                                  theMatrix.GetValue (2, 1) * aTrans.y();
330
331   // Apply rotation
332   const Standard_ShortReal aSin = std::sin (
333     -theParams->Rotation() * static_cast<Standard_ShortReal> (M_PI / 180.0));
334   const Standard_ShortReal aCos = std::cos (
335     -theParams->Rotation() * static_cast<Standard_ShortReal> (M_PI / 180.0));
336
337   BVH_Mat4f aRotationMat;
338   aRotationMat.SetValue (0, 0,  aCos);
339   aRotationMat.SetValue (1, 1,  aCos);
340   aRotationMat.SetValue (0, 1, -aSin);
341   aRotationMat.SetValue (1, 0,  aSin);
342
343   theMatrix = theMatrix * aRotationMat;
344 }
345
346 // =======================================================================
347 // function : convertMaterial
348 // purpose  : Creates ray-tracing material properties
349 // =======================================================================
350 OpenGl_RaytraceMaterial OpenGl_View::convertMaterial (const OpenGl_Aspects* theAspect,
351                                                       const Handle(OpenGl_Context)& theGlContext)
352 {
353   OpenGl_RaytraceMaterial aResMat;
354
355   const Graphic3d_MaterialAspect& aSrcMat = theAspect->Aspect()->FrontMaterial();
356   const OpenGl_Vec3& aMatCol  = theAspect->Aspect()->InteriorColor();
357   const float        aShine   = 128.0f * float(aSrcMat.Shininess());
358
359   const OpenGl_Vec3& aSrcAmb = aSrcMat.AmbientColor();
360   const OpenGl_Vec3& aSrcDif = aSrcMat.DiffuseColor();
361   const OpenGl_Vec3& aSrcSpe = aSrcMat.SpecularColor();
362   const OpenGl_Vec3& aSrcEms = aSrcMat.EmissiveColor();
363   switch (aSrcMat.MaterialType())
364   {
365     case Graphic3d_MATERIAL_ASPECT:
366     {
367       aResMat.Ambient .SetValues (aSrcAmb * aMatCol,  1.0f);
368       aResMat.Diffuse .SetValues (aSrcDif * aMatCol, -1.0f); // -1 is no texture
369       aResMat.Emission.SetValues (aSrcEms * aMatCol,  1.0f);
370       break;
371     }
372     case Graphic3d_MATERIAL_PHYSIC:
373     {
374       aResMat.Ambient .SetValues (aSrcAmb,  1.0f);
375       aResMat.Diffuse .SetValues (aSrcDif, -1.0f); // -1 is no texture
376       aResMat.Emission.SetValues (aSrcEms,  1.0f);
377       break;
378     }
379   }
380
381   {
382     // interior color is always ignored for Specular
383     aResMat.Specular.SetValues (aSrcSpe, aShine);
384     const Standard_ShortReal aMaxRefl = Max (aResMat.Diffuse.x() + aResMat.Specular.x(),
385                                         Max (aResMat.Diffuse.y() + aResMat.Specular.y(),
386                                              aResMat.Diffuse.z() + aResMat.Specular.z()));
387     const Standard_ShortReal aReflectionScale = 0.75f / aMaxRefl;
388     aResMat.Reflection.SetValues (aSrcSpe * aReflectionScale, 0.0f);
389   }
390
391   const float anIndex = (float )aSrcMat.RefractionIndex();
392   aResMat.Transparency = BVH_Vec4f (aSrcMat.Alpha(), aSrcMat.Transparency(),
393                                     anIndex == 0 ? 1.0f : anIndex,
394                                     anIndex == 0 ? 1.0f : 1.0f / anIndex);
395
396   // Serialize physically-based material properties
397   const Graphic3d_BSDF& aBSDF = aSrcMat.BSDF();
398
399   aResMat.BSDF.Kc = aBSDF.Kc;
400   aResMat.BSDF.Ks = aBSDF.Ks;
401   aResMat.BSDF.Kd = BVH_Vec4f (aBSDF.Kd, -1.f); // no texture
402   aResMat.BSDF.Kt = BVH_Vec4f (aBSDF.Kt,  0.f);
403   aResMat.BSDF.Le = BVH_Vec4f (aBSDF.Le,  0.f);
404
405   aResMat.BSDF.Absorption = aBSDF.Absorption;
406
407   aResMat.BSDF.FresnelCoat = aBSDF.FresnelCoat.Serialize ();
408   aResMat.BSDF.FresnelBase = aBSDF.FresnelBase.Serialize ();
409
410   // Handle material textures
411   if (!theAspect->Aspect()->ToMapTexture())
412   {
413     return aResMat;
414   }
415
416   const Handle(OpenGl_TextureSet)& aTextureSet = theAspect->TextureSet (theGlContext);
417   if (aTextureSet.IsNull()
418    || aTextureSet->IsEmpty()
419    || aTextureSet->First().IsNull())
420   {
421     return aResMat;
422   }
423
424   if (theGlContext->HasRayTracingTextures())
425   {
426     const Handle(OpenGl_Texture)& aTexture = aTextureSet->First();
427     buildTextureTransform (aTexture->Sampler()->Parameters(), aResMat.TextureTransform);
428
429     // write texture ID to diffuse w-component
430     aResMat.Diffuse.w() = aResMat.BSDF.Kd.w() = static_cast<Standard_ShortReal> (myRaytraceGeometry.AddTexture (aTexture));
431   }
432   else if (!myIsRaytraceWarnTextures)
433   {
434     theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_PORTABILITY, 0, GL_DEBUG_SEVERITY_HIGH,
435                                "Warning: texturing in Ray-Trace requires GL_ARB_bindless_texture extension which is missing. "
436                                "Please try to update graphics card driver. At the moment textures will be ignored.");
437     myIsRaytraceWarnTextures = Standard_True;
438   }
439
440   return aResMat;
441 }
442
443 // =======================================================================
444 // function : addRaytraceStructure
445 // purpose  : Adds OpenGL structure to ray-traced scene geometry
446 // =======================================================================
447 Standard_Boolean OpenGl_View::addRaytraceStructure (const OpenGl_Structure*       theStructure,
448                                                     const Handle(OpenGl_Context)& theGlContext)
449 {
450   if (!theStructure->IsVisible())
451   {
452     myStructureStates[theStructure] = StructState (theStructure);
453
454     return Standard_True;
455   }
456
457   // Get structure material
458   OpenGl_RaytraceMaterial aDefaultMaterial;
459   Standard_Boolean aResult = addRaytraceGroups (theStructure, aDefaultMaterial, theStructure->Transformation(), theGlContext);
460
461   // Process all connected OpenGL structures
462   const OpenGl_Structure* anInstanced = theStructure->InstancedStructure();
463
464   if (anInstanced != NULL && anInstanced->IsRaytracable())
465   {
466     aResult &= addRaytraceGroups (anInstanced, aDefaultMaterial, theStructure->Transformation(), theGlContext);
467   }
468
469   myStructureStates[theStructure] = StructState (theStructure);
470
471   return aResult;
472 }
473
474 // =======================================================================
475 // function : addRaytraceGroups
476 // purpose  : Adds OpenGL groups to ray-traced scene geometry
477 // =======================================================================
478 Standard_Boolean OpenGl_View::addRaytraceGroups (const OpenGl_Structure*        theStructure,
479                                                  const OpenGl_RaytraceMaterial& theStructMat,
480                                                  const Handle(Geom_Transformation)& theTrsf,
481                                                  const Handle(OpenGl_Context)&  theGlContext)
482 {
483   OpenGl_Mat4 aMat4;
484   for (OpenGl_Structure::GroupIterator aGroupIter (theStructure->Groups()); aGroupIter.More(); aGroupIter.Next())
485   {
486     // Get group material
487     OpenGl_RaytraceMaterial aGroupMaterial;
488     if (aGroupIter.Value()->GlAspects() != NULL)
489     {
490       aGroupMaterial = convertMaterial (aGroupIter.Value()->GlAspects(), theGlContext);
491     }
492
493     Standard_Integer aMatID = static_cast<Standard_Integer> (myRaytraceGeometry.Materials.size());
494
495     // Use group material if available, otherwise use structure material
496     myRaytraceGeometry.Materials.push_back (aGroupIter.Value()->GlAspects() != NULL ? aGroupMaterial : theStructMat);
497
498     // Add OpenGL elements from group (extract primitives arrays and aspects)
499     for (const OpenGl_ElementNode* aNode = aGroupIter.Value()->FirstNode(); aNode != NULL; aNode = aNode->next)
500     {
501       OpenGl_Aspects* anAspect = dynamic_cast<OpenGl_Aspects*> (aNode->elem);
502
503       if (anAspect != NULL)
504       {
505         aMatID = static_cast<Standard_Integer> (myRaytraceGeometry.Materials.size());
506
507         OpenGl_RaytraceMaterial aMaterial = convertMaterial (anAspect, theGlContext);
508
509         myRaytraceGeometry.Materials.push_back (aMaterial);
510       }
511       else
512       {
513         OpenGl_PrimitiveArray* aPrimArray = dynamic_cast<OpenGl_PrimitiveArray*> (aNode->elem);
514
515         if (aPrimArray != NULL)
516         {
517           std::map<Standard_Size, OpenGl_TriangleSet*>::iterator aSetIter = myArrayToTrianglesMap.find (aPrimArray->GetUID());
518
519           if (aSetIter != myArrayToTrianglesMap.end())
520           {
521             OpenGl_TriangleSet* aSet = aSetIter->second;
522             opencascade::handle<BVH_Transform<Standard_ShortReal, 4> > aTransform = new BVH_Transform<Standard_ShortReal, 4>();
523             if (!theTrsf.IsNull())
524             {
525               theTrsf->Trsf().GetMat4 (aMat4);
526               aTransform->SetTransform (aMat4);
527             }
528
529             aSet->SetProperties (aTransform);
530             if (aSet->MaterialIndex() != OpenGl_TriangleSet::INVALID_MATERIAL && aSet->MaterialIndex() != aMatID)
531             {
532               aSet->SetMaterialIndex (aMatID);
533             }
534           }
535           else
536           {
537             if (Handle(OpenGl_TriangleSet) aSet = addRaytracePrimitiveArray (aPrimArray, aMatID, 0))
538             {
539               opencascade::handle<BVH_Transform<Standard_ShortReal, 4> > aTransform = new BVH_Transform<Standard_ShortReal, 4>();
540               if (!theTrsf.IsNull())
541               {
542                 theTrsf->Trsf().GetMat4 (aMat4);
543                 aTransform->SetTransform (aMat4);
544               }
545
546               aSet->SetProperties (aTransform);
547               myRaytraceGeometry.Objects().Append (aSet);
548             }
549           }
550         }
551       }
552     }
553   }
554
555   return Standard_True;
556 }
557
558 // =======================================================================
559 // function : addRaytracePrimitiveArray
560 // purpose  : Adds OpenGL primitive array to ray-traced scene geometry
561 // =======================================================================
562 Handle(OpenGl_TriangleSet) OpenGl_View::addRaytracePrimitiveArray (const OpenGl_PrimitiveArray* theArray,
563                                                                    const Standard_Integer       theMaterial,
564                                                                    const OpenGl_Mat4*           theTransform)
565 {
566   const Handle(Graphic3d_BoundBuffer)& aBounds   = theArray->Bounds();
567   const Handle(Graphic3d_IndexBuffer)& anIndices = theArray->Indices();
568   const Handle(Graphic3d_Buffer)&      anAttribs = theArray->Attributes();
569
570   if (theArray->DrawMode() < GL_TRIANGLES
571   #ifndef GL_ES_VERSION_2_0
572    || theArray->DrawMode() > GL_POLYGON
573   #else
574    || theArray->DrawMode() > GL_TRIANGLE_FAN
575   #endif
576    || anAttribs.IsNull())
577   {
578     return Handle(OpenGl_TriangleSet)();
579   }
580
581   OpenGl_Mat4 aNormalMatrix;
582   if (theTransform != NULL)
583   {
584     Standard_ASSERT_RETURN (theTransform->Inverted (aNormalMatrix),
585       "Error: Failed to compute normal transformation matrix", NULL);
586
587     aNormalMatrix.Transpose();
588   }
589
590   Handle(OpenGl_TriangleSet) aSet = new OpenGl_TriangleSet (theArray->GetUID(), myRaytraceBVHBuilder);
591   {
592     aSet->Vertices.reserve (anAttribs->NbElements);
593     aSet->Normals.reserve  (anAttribs->NbElements);
594     aSet->TexCrds.reserve  (anAttribs->NbElements);
595
596     const size_t aVertFrom = aSet->Vertices.size();
597
598     Standard_Integer anAttribIndex = 0;
599     Standard_Size anAttribStride = 0;
600     if (const Standard_Byte* aPosData = anAttribs->AttributeData (Graphic3d_TOA_POS, anAttribIndex, anAttribStride))
601     {
602       const Graphic3d_Attribute& anAttrib = anAttribs->Attribute (anAttribIndex);
603       if (anAttrib.DataType == Graphic3d_TOD_VEC2
604        || anAttrib.DataType == Graphic3d_TOD_VEC3
605        || anAttrib.DataType == Graphic3d_TOD_VEC4)
606       {
607         for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
608         {
609           const float* aCoords = reinterpret_cast<const float*> (aPosData + anAttribStride * aVertIter);
610           aSet->Vertices.push_back (BVH_Vec3f (aCoords[0], aCoords[1], anAttrib.DataType != Graphic3d_TOD_VEC2 ? aCoords[2] : 0.0f));
611         }
612       }
613     }
614     if (const Standard_Byte* aNormData = anAttribs->AttributeData (Graphic3d_TOA_NORM, anAttribIndex, anAttribStride))
615     {
616       const Graphic3d_Attribute& anAttrib = anAttribs->Attribute (anAttribIndex);
617       if (anAttrib.DataType == Graphic3d_TOD_VEC3
618        || anAttrib.DataType == Graphic3d_TOD_VEC4)
619       {
620         for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
621         {
622           aSet->Normals.push_back (*reinterpret_cast<const Graphic3d_Vec3*> (aNormData + anAttribStride * aVertIter));
623         }
624       }
625     }
626     if (const Standard_Byte* aTexData = anAttribs->AttributeData (Graphic3d_TOA_UV, anAttribIndex, anAttribStride))
627     {
628       const Graphic3d_Attribute& anAttrib = anAttribs->Attribute (anAttribIndex);
629       if (anAttrib.DataType == Graphic3d_TOD_VEC2)
630       {
631         for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
632         {
633           aSet->TexCrds.push_back (*reinterpret_cast<const Graphic3d_Vec2*> (aTexData + anAttribStride * aVertIter));
634         }
635       }
636     }
637
638     if (aSet->Normals.size() != aSet->Vertices.size())
639     {
640       for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
641       {
642         aSet->Normals.push_back (BVH_Vec3f());
643       }
644     }
645
646     if (aSet->TexCrds.size() != aSet->Vertices.size())
647     {
648       for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
649       {
650         aSet->TexCrds.push_back (BVH_Vec2f());
651       }
652     }
653
654     if (theTransform != NULL)
655     {
656       for (size_t aVertIter = aVertFrom; aVertIter < aSet->Vertices.size(); ++aVertIter)
657       {
658         BVH_Vec3f& aVertex = aSet->Vertices[aVertIter];
659
660         BVH_Vec4f aTransVertex = *theTransform *
661           BVH_Vec4f (aVertex.x(), aVertex.y(), aVertex.z(), 1.f);
662
663         aVertex = BVH_Vec3f (aTransVertex.x(), aTransVertex.y(), aTransVertex.z());
664       }
665       for (size_t aVertIter = aVertFrom; aVertIter < aSet->Normals.size(); ++aVertIter)
666       {
667         BVH_Vec3f& aNormal = aSet->Normals[aVertIter];
668
669         BVH_Vec4f aTransNormal = aNormalMatrix *
670           BVH_Vec4f (aNormal.x(), aNormal.y(), aNormal.z(), 0.f);
671
672         aNormal = BVH_Vec3f (aTransNormal.x(), aTransNormal.y(), aTransNormal.z());
673       }
674     }
675
676     if (!aBounds.IsNull())
677     {
678       for (Standard_Integer aBound = 0, aBoundStart = 0; aBound < aBounds->NbBounds; ++aBound)
679       {
680         const Standard_Integer aVertNum = aBounds->Bounds[aBound];
681
682         if (!addRaytraceVertexIndices (*aSet, theMaterial, aVertNum, aBoundStart, *theArray))
683         {
684           aSet.Nullify();
685           return Handle(OpenGl_TriangleSet)();
686         }
687
688         aBoundStart += aVertNum;
689       }
690     }
691     else
692     {
693       const Standard_Integer aVertNum = !anIndices.IsNull() ? anIndices->NbElements : anAttribs->NbElements;
694
695       if (!addRaytraceVertexIndices (*aSet, theMaterial, aVertNum, 0, *theArray))
696       {
697         aSet.Nullify();
698         return Handle(OpenGl_TriangleSet)();
699       }
700     }
701   }
702
703   if (aSet->Size() != 0)
704   {
705     aSet->MarkDirty();
706   }
707
708   return aSet;
709 }
710
711 // =======================================================================
712 // function : addRaytraceVertexIndices
713 // purpose  : Adds vertex indices to ray-traced scene geometry
714 // =======================================================================
715 Standard_Boolean OpenGl_View::addRaytraceVertexIndices (OpenGl_TriangleSet&                  theSet,
716                                                         const Standard_Integer               theMatID,
717                                                         const Standard_Integer               theCount,
718                                                         const Standard_Integer               theOffset,
719                                                         const OpenGl_PrimitiveArray&         theArray)
720 {
721   switch (theArray.DrawMode())
722   {
723     case GL_TRIANGLES:      return addRaytraceTriangleArray        (theSet, theMatID, theCount, theOffset, theArray.Indices());
724     case GL_TRIANGLE_FAN:   return addRaytraceTriangleFanArray     (theSet, theMatID, theCount, theOffset, theArray.Indices());
725     case GL_TRIANGLE_STRIP: return addRaytraceTriangleStripArray   (theSet, theMatID, theCount, theOffset, theArray.Indices());
726   #if !defined(GL_ES_VERSION_2_0)
727     case GL_QUAD_STRIP:     return addRaytraceQuadrangleStripArray (theSet, theMatID, theCount, theOffset, theArray.Indices());
728     case GL_QUADS:          return addRaytraceQuadrangleArray      (theSet, theMatID, theCount, theOffset, theArray.Indices());
729     case GL_POLYGON:        return addRaytracePolygonArray         (theSet, theMatID, theCount, theOffset, theArray.Indices());
730   #endif
731   }
732
733   return Standard_False;
734 }
735
736 // =======================================================================
737 // function : addRaytraceTriangleArray
738 // purpose  : Adds OpenGL triangle array to ray-traced scene geometry
739 // =======================================================================
740 Standard_Boolean OpenGl_View::addRaytraceTriangleArray (OpenGl_TriangleSet&                  theSet,
741                                                         const Standard_Integer               theMatID,
742                                                         const Standard_Integer               theCount,
743                                                         const Standard_Integer               theOffset,
744                                                         const Handle(Graphic3d_IndexBuffer)& theIndices)
745 {
746   if (theCount < 3)
747   {
748     return Standard_True;
749   }
750
751   theSet.Elements.reserve (theSet.Elements.size() + theCount / 3);
752
753   if (!theIndices.IsNull())
754   {
755     for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; aVert += 3)
756     {
757       theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0),
758                                             theIndices->Index (aVert + 1),
759                                             theIndices->Index (aVert + 2),
760                                             theMatID));
761     }
762   }
763   else
764   {
765     for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; aVert += 3)
766     {
767       theSet.Elements.push_back (BVH_Vec4i (aVert + 0, aVert + 1, aVert + 2, theMatID));
768     }
769   }
770
771   return Standard_True;
772 }
773
774 // =======================================================================
775 // function : addRaytraceTriangleFanArray
776 // purpose  : Adds OpenGL triangle fan array to ray-traced scene geometry
777 // =======================================================================
778 Standard_Boolean OpenGl_View::addRaytraceTriangleFanArray (OpenGl_TriangleSet&                  theSet,
779                                                            const Standard_Integer               theMatID,
780                                                            const Standard_Integer               theCount,
781                                                            const Standard_Integer               theOffset,
782                                                            const Handle(Graphic3d_IndexBuffer)& theIndices)
783 {
784   if (theCount < 3)
785   {
786     return Standard_True;
787   }
788
789   theSet.Elements.reserve (theSet.Elements.size() + theCount - 2);
790
791   if (!theIndices.IsNull())
792   {
793     for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
794     {
795       theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (theOffset),
796                                             theIndices->Index (aVert + 1),
797                                             theIndices->Index (aVert + 2),
798                                             theMatID));
799     }
800   }
801   else
802   {
803     for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
804     {
805       theSet.Elements.push_back (BVH_Vec4i (theOffset,
806                                             aVert + 1,
807                                             aVert + 2,
808                                             theMatID));
809     }
810   }
811
812   return Standard_True;
813 }
814
815 // =======================================================================
816 // function : addRaytraceTriangleStripArray
817 // purpose  : Adds OpenGL triangle strip array to ray-traced scene geometry
818 // =======================================================================
819 Standard_Boolean OpenGl_View::addRaytraceTriangleStripArray (OpenGl_TriangleSet&                  theSet,
820                                                              const Standard_Integer               theMatID,
821                                                              const Standard_Integer               theCount,
822                                                              const Standard_Integer               theOffset,
823                                                              const Handle(Graphic3d_IndexBuffer)& theIndices)
824 {
825   if (theCount < 3)
826   {
827     return Standard_True;
828   }
829
830   theSet.Elements.reserve (theSet.Elements.size() + theCount - 2);
831
832   if (!theIndices.IsNull())
833   {
834     for (Standard_Integer aVert = theOffset, aCW = 0; aVert < theOffset + theCount - 2; ++aVert, aCW = (aCW + 1) % 2)
835     {
836       theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + (aCW ? 1 : 0)),
837                                             theIndices->Index (aVert + (aCW ? 0 : 1)),
838                                             theIndices->Index (aVert + 2),
839                                             theMatID));
840     }
841   }
842   else
843   {
844     for (Standard_Integer aVert = theOffset, aCW = 0; aVert < theOffset + theCount - 2; ++aVert, aCW = (aCW + 1) % 2)
845     {
846       theSet.Elements.push_back (BVH_Vec4i (aVert + (aCW ? 1 : 0),
847                                             aVert + (aCW ? 0 : 1),
848                                             aVert + 2,
849                                             theMatID));
850     }
851   }
852
853   return Standard_True;
854 }
855
856 // =======================================================================
857 // function : addRaytraceQuadrangleArray
858 // purpose  : Adds OpenGL quad array to ray-traced scene geometry
859 // =======================================================================
860 Standard_Boolean OpenGl_View::addRaytraceQuadrangleArray (OpenGl_TriangleSet&                  theSet,
861                                                           const Standard_Integer               theMatID,
862                                                           const Standard_Integer               theCount,
863                                                           const Standard_Integer               theOffset,
864                                                           const Handle(Graphic3d_IndexBuffer)& theIndices)
865 {
866   if (theCount < 4)
867   {
868     return Standard_True;
869   }
870
871   theSet.Elements.reserve (theSet.Elements.size() + theCount / 2);
872
873   if (!theIndices.IsNull())
874   {
875     for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 4)
876     {
877       theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0),
878                                             theIndices->Index (aVert + 1),
879                                             theIndices->Index (aVert + 2),
880                                             theMatID));
881       theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0),
882                                             theIndices->Index (aVert + 2),
883                                             theIndices->Index (aVert + 3),
884                                             theMatID));
885     }
886   }
887   else
888   {
889     for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 4)
890     {
891       theSet.Elements.push_back (BVH_Vec4i (aVert + 0, aVert + 1, aVert + 2,
892                                             theMatID));
893       theSet.Elements.push_back (BVH_Vec4i (aVert + 0, aVert + 2, aVert + 3,
894                                             theMatID));
895     }
896   }
897
898   return Standard_True;
899 }
900
901 // =======================================================================
902 // function : addRaytraceQuadrangleStripArray
903 // purpose  : Adds OpenGL quad strip array to ray-traced scene geometry
904 // =======================================================================
905 Standard_Boolean OpenGl_View::addRaytraceQuadrangleStripArray (OpenGl_TriangleSet&                  theSet,
906                                                                const Standard_Integer               theMatID,
907                                                                const Standard_Integer               theCount,
908                                                                const Standard_Integer               theOffset,
909                                                                const Handle(Graphic3d_IndexBuffer)& theIndices)
910 {
911   if (theCount < 4)
912   {
913     return Standard_True;
914   }
915
916   theSet.Elements.reserve (theSet.Elements.size() + 2 * theCount - 6);
917
918   if (!theIndices.IsNull())
919   {
920     for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 2)
921     {
922       theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0),
923                                             theIndices->Index (aVert + 1),
924                                             theIndices->Index (aVert + 2),
925                                             theMatID));
926
927       theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 1),
928                                             theIndices->Index (aVert + 3),
929                                             theIndices->Index (aVert + 2),
930                                             theMatID));
931     }
932   }
933   else
934   {
935     for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 2)
936     {
937       theSet.Elements.push_back (BVH_Vec4i (aVert + 0,
938                                             aVert + 1,
939                                             aVert + 2,
940                                             theMatID));
941
942       theSet.Elements.push_back (BVH_Vec4i (aVert + 1,
943                                             aVert + 3,
944                                             aVert + 2,
945                                             theMatID));
946     }
947   }
948
949   return Standard_True;
950 }
951
952 // =======================================================================
953 // function : addRaytracePolygonArray
954 // purpose  : Adds OpenGL polygon array to ray-traced scene geometry
955 // =======================================================================
956 Standard_Boolean OpenGl_View::addRaytracePolygonArray (OpenGl_TriangleSet&                  theSet,
957                                                        const Standard_Integer               theMatID,
958                                                        const Standard_Integer               theCount,
959                                                        const Standard_Integer               theOffset,
960                                                        const Handle(Graphic3d_IndexBuffer)& theIndices)
961 {
962   if (theCount < 3)
963   {
964     return Standard_True;
965   }
966
967   theSet.Elements.reserve (theSet.Elements.size() + theCount - 2);
968
969   if (!theIndices.IsNull())
970   {
971     for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
972     {
973       theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (theOffset),
974                                             theIndices->Index (aVert + 1),
975                                             theIndices->Index (aVert + 2),
976                                             theMatID));
977     }
978   }
979   else
980   {
981     for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
982     {
983       theSet.Elements.push_back (BVH_Vec4i (theOffset,
984                                             aVert + 1,
985                                             aVert + 2,
986                                             theMatID));
987     }
988   }
989
990   return Standard_True;
991 }
992
993 const TCollection_AsciiString OpenGl_View::ShaderSource::EMPTY_PREFIX;
994
995 // =======================================================================
996 // function : Source
997 // purpose  : Returns shader source combined with prefix
998 // =======================================================================
999 TCollection_AsciiString OpenGl_View::ShaderSource::Source() const
1000 {
1001   const TCollection_AsciiString aVersion = "#version 140";
1002
1003   if (myPrefix.IsEmpty())
1004   {
1005     return aVersion + "\n" + mySource;
1006   }
1007
1008   return aVersion + "\n" + myPrefix + "\n" + mySource;
1009 }
1010
1011 // =======================================================================
1012 // function : LoadFromFiles
1013 // purpose  : Loads shader source from specified files
1014 // =======================================================================
1015 Standard_Boolean OpenGl_View::ShaderSource::LoadFromFiles (const TCollection_AsciiString* theFileNames,
1016                                                            const TCollection_AsciiString& thePrefix)
1017 {
1018   myError.Clear();
1019   mySource.Clear();
1020   myPrefix = thePrefix;
1021
1022   TCollection_AsciiString aMissingFiles;
1023   for (Standard_Integer anIndex = 0; !theFileNames[anIndex].IsEmpty(); ++anIndex)
1024   {
1025     OSD_File aFile (theFileNames[anIndex]);
1026     if (aFile.Exists())
1027     {
1028       aFile.Open (OSD_ReadOnly, OSD_Protection());
1029     }
1030     if (!aFile.IsOpen())
1031     {
1032       if (!aMissingFiles.IsEmpty())
1033       {
1034         aMissingFiles += ", ";
1035       }
1036       aMissingFiles += TCollection_AsciiString("'") + theFileNames[anIndex] + "'";
1037       continue;
1038     }
1039     else if (!aMissingFiles.IsEmpty())
1040     {
1041       aFile.Close();
1042       continue;
1043     }
1044
1045     TCollection_AsciiString aSource;
1046     aFile.Read (aSource, (Standard_Integer) aFile.Size());
1047     if (!aSource.IsEmpty())
1048     {
1049       mySource += TCollection_AsciiString ("\n") + aSource;
1050     }
1051     aFile.Close();
1052   }
1053
1054   if (!aMissingFiles.IsEmpty())
1055   {
1056     myError = TCollection_AsciiString("Shader files ") + aMissingFiles + " are missing or inaccessible";
1057     return Standard_False;
1058   }
1059   return Standard_True;
1060 }
1061
1062 // =======================================================================
1063 // function : LoadFromStrings
1064 // purpose  :
1065 // =======================================================================
1066 Standard_Boolean OpenGl_View::ShaderSource::LoadFromStrings (const TCollection_AsciiString* theStrings,
1067                                                              const TCollection_AsciiString& thePrefix)
1068 {
1069   myError.Clear();
1070   mySource.Clear();
1071   myPrefix = thePrefix;
1072
1073   for (Standard_Integer anIndex = 0; !theStrings[anIndex].IsEmpty(); ++anIndex)
1074   {
1075     TCollection_AsciiString aSource = theStrings[anIndex];
1076     if (!aSource.IsEmpty())
1077     {
1078       mySource += TCollection_AsciiString ("\n") + aSource;
1079     }
1080   }
1081   return Standard_True;
1082 }
1083
1084 // =======================================================================
1085 // function : generateShaderPrefix
1086 // purpose  : Generates shader prefix based on current ray-tracing options
1087 // =======================================================================
1088 TCollection_AsciiString OpenGl_View::generateShaderPrefix (const Handle(OpenGl_Context)& theGlContext) const
1089 {
1090   TCollection_AsciiString aPrefixString =
1091     TCollection_AsciiString ("#define STACK_SIZE ") + TCollection_AsciiString (myRaytraceParameters.StackSize) + "\n" +
1092     TCollection_AsciiString ("#define NB_BOUNCES ") + TCollection_AsciiString (myRaytraceParameters.NbBounces);
1093
1094   if (myRaytraceParameters.TransparentShadows)
1095   {
1096     aPrefixString += TCollection_AsciiString ("\n#define TRANSPARENT_SHADOWS");
1097   }
1098
1099   // If OpenGL driver supports bindless textures and texturing
1100   // is actually used, activate texturing in ray-tracing mode
1101   if (myRaytraceParameters.UseBindlessTextures && theGlContext->arbTexBindless != NULL)
1102   {
1103     aPrefixString += TCollection_AsciiString ("\n#define USE_TEXTURES") +
1104       TCollection_AsciiString ("\n#define MAX_TEX_NUMBER ") + TCollection_AsciiString (OpenGl_RaytraceGeometry::MAX_TEX_NUMBER);
1105   }
1106
1107   if (myRaytraceParameters.GlobalIllumination) // path tracing activated
1108   {
1109     aPrefixString += TCollection_AsciiString ("\n#define PATH_TRACING");
1110
1111     if (myRaytraceParameters.AdaptiveScreenSampling) // adaptive screen sampling requested
1112     {
1113       if (theGlContext->IsGlGreaterEqual (4, 4))
1114       {
1115         aPrefixString += TCollection_AsciiString ("\n#define ADAPTIVE_SAMPLING");
1116         if (myRaytraceParameters.AdaptiveScreenSamplingAtomic
1117          && theGlContext->CheckExtension ("GL_NV_shader_atomic_float"))
1118         {
1119           aPrefixString += TCollection_AsciiString ("\n#define ADAPTIVE_SAMPLING_ATOMIC");
1120         }
1121       }
1122     }
1123
1124     if (myRaytraceParameters.TwoSidedBsdfModels) // two-sided BSDFs requested
1125     {
1126       aPrefixString += TCollection_AsciiString ("\n#define TWO_SIDED_BXDF");
1127     }
1128
1129     switch (myRaytraceParameters.ToneMappingMethod)
1130     {
1131       case Graphic3d_ToneMappingMethod_Disabled:
1132         break;
1133       case Graphic3d_ToneMappingMethod_Filmic:
1134         aPrefixString += TCollection_AsciiString ("\n#define TONE_MAPPING_FILMIC");
1135         break;
1136     }
1137   }
1138
1139   if (myRaytraceParameters.DepthOfField)
1140   {
1141     aPrefixString += TCollection_AsciiString("\n#define DEPTH_OF_FIELD");
1142   }
1143
1144   return aPrefixString;
1145 }
1146
1147 // =======================================================================
1148 // function : safeFailBack
1149 // purpose  : Performs safe exit when shaders initialization fails
1150 // =======================================================================
1151 Standard_Boolean OpenGl_View::safeFailBack (const TCollection_ExtendedString& theMessage,
1152                                             const Handle(OpenGl_Context)&     theGlContext)
1153 {
1154   theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1155     GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, theMessage);
1156
1157   myRaytraceInitStatus = OpenGl_RT_FAIL;
1158
1159   releaseRaytraceResources (theGlContext);
1160
1161   return Standard_False;
1162 }
1163
1164 // =======================================================================
1165 // function : initShader
1166 // purpose  : Creates new shader object with specified source
1167 // =======================================================================
1168 Handle(OpenGl_ShaderObject) OpenGl_View::initShader (const GLenum                  theType,
1169                                                      const ShaderSource&           theSource,
1170                                                      const Handle(OpenGl_Context)& theGlContext)
1171 {
1172   Handle(OpenGl_ShaderObject) aShader = new OpenGl_ShaderObject (theType);
1173   if (!aShader->Create (theGlContext))
1174   {
1175     theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH,
1176                                TCollection_ExtendedString ("Error: Failed to create ") +
1177                                (theType == GL_VERTEX_SHADER ? "vertex" : "fragment") + " shader object");
1178     aShader->Release (theGlContext.get());
1179     return Handle(OpenGl_ShaderObject)();
1180   }
1181
1182   if (!aShader->LoadAndCompile (theGlContext, "", theSource.Source()))
1183   {
1184     aShader->Release (theGlContext.get());
1185     return Handle(OpenGl_ShaderObject)();
1186   }
1187   return aShader;
1188 }
1189
1190 // =======================================================================
1191 // function : initProgram
1192 // purpose  : Creates GLSL program from the given shader objects
1193 // =======================================================================
1194 Handle(OpenGl_ShaderProgram) OpenGl_View::initProgram (const Handle(OpenGl_Context)&      theGlContext,
1195                                                        const Handle(OpenGl_ShaderObject)& theVertShader,
1196                                                        const Handle(OpenGl_ShaderObject)& theFragShader,
1197                                                        const TCollection_AsciiString& theName)
1198 {
1199   const TCollection_AsciiString anId = TCollection_AsciiString("occt_rt_") + theName;
1200   Handle(OpenGl_ShaderProgram) aProgram = new OpenGl_ShaderProgram(Handle(Graphic3d_ShaderProgram)(), anId);
1201
1202   if (!aProgram->Create (theGlContext))
1203   {
1204     theVertShader->Release (theGlContext.operator->());
1205
1206     theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1207       GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, "Failed to create shader program");
1208
1209     return Handle(OpenGl_ShaderProgram)();
1210   }
1211
1212   if (!aProgram->AttachShader (theGlContext, theVertShader)
1213    || !aProgram->AttachShader (theGlContext, theFragShader))
1214   {
1215     theVertShader->Release (theGlContext.operator->());
1216
1217     theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1218       GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, "Failed to attach shader objects");
1219
1220     return Handle(OpenGl_ShaderProgram)();
1221   }
1222
1223   aProgram->SetAttributeName (theGlContext, Graphic3d_TOA_POS, "occVertex");
1224
1225   TCollection_AsciiString aLinkLog;
1226
1227   if (!aProgram->Link (theGlContext))
1228   {
1229     aProgram->FetchInfoLog (theGlContext, aLinkLog);
1230
1231     const TCollection_ExtendedString aMessage = TCollection_ExtendedString (
1232       "Failed to link shader program:\n") + aLinkLog;
1233
1234     theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1235       GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, aMessage);
1236
1237     return Handle(OpenGl_ShaderProgram)();
1238   }
1239   else if (theGlContext->caps->glslWarnings)
1240   {
1241     aProgram->FetchInfoLog (theGlContext, aLinkLog);
1242     if (!aLinkLog.IsEmpty() && !aLinkLog.IsEqual ("No errors.\n"))
1243     {
1244       const TCollection_ExtendedString aMessage = TCollection_ExtendedString (
1245         "Shader program was linked with following warnings:\n") + aLinkLog;
1246
1247       theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1248         GL_DEBUG_TYPE_PORTABILITY, 0, GL_DEBUG_SEVERITY_LOW, aMessage);
1249     }
1250   }
1251
1252   return aProgram;
1253 }
1254
1255 // =======================================================================
1256 // function : initRaytraceResources
1257 // purpose  : Initializes OpenGL/GLSL shader programs
1258 // =======================================================================
1259 Standard_Boolean OpenGl_View::initRaytraceResources (const Standard_Integer theSizeX,
1260                                                      const Standard_Integer theSizeY,
1261                                                      const Handle(OpenGl_Context)& theGlContext)
1262 {
1263   if (myRaytraceInitStatus == OpenGl_RT_FAIL)
1264   {
1265     return Standard_False;
1266   }
1267
1268   Standard_Boolean aToRebuildShaders = Standard_False;
1269
1270   if (myRenderParams.RebuildRayTracingShaders) // requires complete re-initialization
1271   {
1272     myRaytraceInitStatus = OpenGl_RT_NONE;
1273     releaseRaytraceResources (theGlContext, Standard_True);
1274     myRenderParams.RebuildRayTracingShaders = Standard_False; // clear rebuilding flag
1275   }
1276
1277   if (myRaytraceInitStatus == OpenGl_RT_INIT)
1278   {
1279     if (!myIsRaytraceDataValid)
1280     {
1281       return Standard_True;
1282     }
1283
1284     const Standard_Integer aRequiredStackSize =
1285       myRaytraceGeometry.TopLevelTreeDepth() + myRaytraceGeometry.BotLevelTreeDepth();
1286
1287     if (myRaytraceParameters.StackSize < aRequiredStackSize)
1288     {
1289       myRaytraceParameters.StackSize = Max (aRequiredStackSize, THE_DEFAULT_STACK_SIZE);
1290
1291       aToRebuildShaders = Standard_True;
1292     }
1293     else
1294     {
1295       if (aRequiredStackSize < myRaytraceParameters.StackSize)
1296       {
1297         if (myRaytraceParameters.StackSize > THE_DEFAULT_STACK_SIZE)
1298         {
1299           myRaytraceParameters.StackSize = Max (aRequiredStackSize, THE_DEFAULT_STACK_SIZE);
1300           aToRebuildShaders = Standard_True;
1301         }
1302       }
1303     }
1304
1305     if (myRenderParams.RaytracingDepth             != myRaytraceParameters.NbBounces
1306      || myRenderParams.IsTransparentShadowEnabled  != myRaytraceParameters.TransparentShadows
1307      || myRenderParams.IsGlobalIlluminationEnabled != myRaytraceParameters.GlobalIllumination
1308      || myRenderParams.TwoSidedBsdfModels          != myRaytraceParameters.TwoSidedBsdfModels
1309      || myRaytraceGeometry.HasTextures()           != myRaytraceParameters.UseBindlessTextures)
1310     {
1311       myRaytraceParameters.NbBounces           = myRenderParams.RaytracingDepth;
1312       myRaytraceParameters.TransparentShadows  = myRenderParams.IsTransparentShadowEnabled;
1313       myRaytraceParameters.GlobalIllumination  = myRenderParams.IsGlobalIlluminationEnabled;
1314       myRaytraceParameters.TwoSidedBsdfModels  = myRenderParams.TwoSidedBsdfModels;
1315       myRaytraceParameters.UseBindlessTextures = myRaytraceGeometry.HasTextures();
1316       aToRebuildShaders = Standard_True;
1317     }
1318
1319     if (myRenderParams.AdaptiveScreenSampling       != myRaytraceParameters.AdaptiveScreenSampling
1320      || myRenderParams.AdaptiveScreenSamplingAtomic != myRaytraceParameters.AdaptiveScreenSamplingAtomic)
1321     {
1322       myRaytraceParameters.AdaptiveScreenSampling       = myRenderParams.AdaptiveScreenSampling;
1323       myRaytraceParameters.AdaptiveScreenSamplingAtomic = myRenderParams.AdaptiveScreenSamplingAtomic;
1324       if (myRenderParams.AdaptiveScreenSampling) // adaptive sampling was requested
1325       {
1326         if (!theGlContext->HasRayTracingAdaptiveSampling())
1327         {
1328           // disable the feature if it is not supported
1329           myRaytraceParameters.AdaptiveScreenSampling = myRenderParams.AdaptiveScreenSampling = Standard_False;
1330           theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_PORTABILITY, 0, GL_DEBUG_SEVERITY_LOW,
1331                                      "Adaptive sampling is not supported (OpenGL 4.4 is missing)");
1332         }
1333         else if (myRaytraceParameters.AdaptiveScreenSamplingAtomic
1334              && !theGlContext->HasRayTracingAdaptiveSamplingAtomic())
1335         {
1336           // disable the feature if it is not supported
1337           myRaytraceParameters.AdaptiveScreenSamplingAtomic = myRenderParams.AdaptiveScreenSamplingAtomic = Standard_False;
1338           theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_PORTABILITY, 0, GL_DEBUG_SEVERITY_LOW,
1339                                      "Atomic adaptive sampling is not supported (GL_NV_shader_atomic_float is missing)");
1340         }
1341       }
1342
1343       aToRebuildShaders = Standard_True;
1344     }
1345     myTileSampler.SetSize (myRenderParams, myRaytraceParameters.AdaptiveScreenSampling ? Graphic3d_Vec2i (theSizeX, theSizeY) : Graphic3d_Vec2i (0, 0));
1346
1347     const bool toEnableDof = !myCamera->IsOrthographic() && myRaytraceParameters.GlobalIllumination;
1348     if (myRaytraceParameters.DepthOfField != toEnableDof)
1349     {
1350       myRaytraceParameters.DepthOfField = toEnableDof;
1351       aToRebuildShaders = Standard_True;
1352     }
1353
1354     if (myRenderParams.ToneMappingMethod != myRaytraceParameters.ToneMappingMethod)
1355     {
1356       myRaytraceParameters.ToneMappingMethod = myRenderParams.ToneMappingMethod;
1357       aToRebuildShaders = true;
1358     }
1359
1360     if (aToRebuildShaders)
1361     {
1362       // Reject accumulated frames
1363       myAccumFrames = 0;
1364
1365       // Environment map should be updated
1366       myToUpdateEnvironmentMap = Standard_True;
1367
1368       const TCollection_AsciiString aPrefixString = generateShaderPrefix (theGlContext);
1369
1370 #ifdef RAY_TRACE_PRINT_INFO
1371       std::cout << "GLSL prefix string:" << std::endl << aPrefixString << std::endl;
1372 #endif
1373
1374       myRaytraceShaderSource.SetPrefix (aPrefixString);
1375       myPostFSAAShaderSource.SetPrefix (aPrefixString);
1376       myOutImageShaderSource.SetPrefix (aPrefixString);
1377
1378       if (!myRaytraceShader->LoadAndCompile (theGlContext, myRaytraceProgram->ResourceId(), myRaytraceShaderSource.Source())
1379        || !myPostFSAAShader->LoadAndCompile (theGlContext, myPostFSAAProgram->ResourceId(), myPostFSAAShaderSource.Source())
1380        || !myOutImageShader->LoadAndCompile (theGlContext, myOutImageProgram->ResourceId(), myOutImageShaderSource.Source()))
1381       {
1382         return safeFailBack ("Failed to compile ray-tracing fragment shaders", theGlContext);
1383       }
1384
1385       myRaytraceProgram->SetAttributeName (theGlContext, Graphic3d_TOA_POS, "occVertex");
1386       myPostFSAAProgram->SetAttributeName (theGlContext, Graphic3d_TOA_POS, "occVertex");
1387       myOutImageProgram->SetAttributeName (theGlContext, Graphic3d_TOA_POS, "occVertex");
1388
1389       if (!myRaytraceProgram->Link (theGlContext)
1390        || !myPostFSAAProgram->Link (theGlContext)
1391        || !myOutImageProgram->Link (theGlContext))
1392       {
1393         return safeFailBack ("Failed to initialize vertex attributes for ray-tracing program", theGlContext);
1394       }
1395     }
1396   }
1397
1398   if (myRaytraceInitStatus == OpenGl_RT_NONE)
1399   {
1400     myAccumFrames = 0; // accumulation should be restarted
1401
1402     if (!theGlContext->IsGlGreaterEqual (3, 1))
1403     {
1404       return safeFailBack ("Ray-tracing requires OpenGL 3.1 and higher", theGlContext);
1405     }
1406     else if (!theGlContext->arbTboRGB32)
1407     {
1408       return safeFailBack ("Ray-tracing requires OpenGL 4.0+ or GL_ARB_texture_buffer_object_rgb32 extension", theGlContext);
1409     }
1410     else if (!theGlContext->arbFBOBlit)
1411     {
1412       return safeFailBack ("Ray-tracing requires EXT_framebuffer_blit extension", theGlContext);
1413     }
1414
1415     myRaytraceParameters.NbBounces = myRenderParams.RaytracingDepth;
1416
1417     const TCollection_AsciiString aShaderFolder = Graphic3d_ShaderProgram::ShadersFolder();
1418     if (myIsRaytraceDataValid)
1419     {
1420       myRaytraceParameters.StackSize = Max (THE_DEFAULT_STACK_SIZE,
1421         myRaytraceGeometry.TopLevelTreeDepth() + myRaytraceGeometry.BotLevelTreeDepth());
1422     }
1423
1424     const TCollection_AsciiString aPrefixString  = generateShaderPrefix (theGlContext);
1425
1426 #ifdef RAY_TRACE_PRINT_INFO
1427     std::cout << "GLSL prefix string:" << std::endl << aPrefixString << std::endl;
1428 #endif
1429
1430     ShaderSource aBasicVertShaderSrc;
1431     {
1432       if (!aShaderFolder.IsEmpty())
1433       {
1434         const TCollection_AsciiString aFiles[] = { aShaderFolder + "/RaytraceBase.vs", "" };
1435         if (!aBasicVertShaderSrc.LoadFromFiles (aFiles))
1436         {
1437           return safeFailBack (aBasicVertShaderSrc.ErrorDescription(), theGlContext);
1438         }
1439       }
1440       else
1441       {
1442         const TCollection_AsciiString aSrcShaders[] = { Shaders_RaytraceBase_vs, "" };
1443         aBasicVertShaderSrc.LoadFromStrings (aSrcShaders);
1444       }
1445     }
1446
1447     {
1448       if (!aShaderFolder.IsEmpty())
1449       {
1450         const TCollection_AsciiString aFiles[] = { aShaderFolder + "/RaytraceBase.fs",
1451                                                    aShaderFolder + "/PathtraceBase.fs",
1452                                                    aShaderFolder + "/RaytraceRender.fs",
1453                                                    "" };
1454         if (!myRaytraceShaderSource.LoadFromFiles (aFiles, aPrefixString))
1455         {
1456           return safeFailBack (myRaytraceShaderSource.ErrorDescription(), theGlContext);
1457         }
1458       }
1459       else
1460       {
1461         const TCollection_AsciiString aSrcShaders[] = { Shaders_RaytraceBase_fs,
1462                                                         Shaders_PathtraceBase_fs,
1463                                                         Shaders_RaytraceRender_fs,
1464                                                         "" };
1465         myRaytraceShaderSource.LoadFromStrings (aSrcShaders, aPrefixString);
1466       }
1467
1468       Handle(OpenGl_ShaderObject) aBasicVertShader = initShader (GL_VERTEX_SHADER, aBasicVertShaderSrc, theGlContext);
1469       if (aBasicVertShader.IsNull())
1470       {
1471         return safeFailBack ("Failed to initialize ray-trace vertex shader", theGlContext);
1472       }
1473
1474       myRaytraceShader = initShader (GL_FRAGMENT_SHADER, myRaytraceShaderSource, theGlContext);
1475       if (myRaytraceShader.IsNull())
1476       {
1477         aBasicVertShader->Release (theGlContext.operator->());
1478         return safeFailBack ("Failed to initialize ray-trace fragment shader", theGlContext);
1479       }
1480
1481       myRaytraceProgram = initProgram (theGlContext, aBasicVertShader, myRaytraceShader, "main");
1482       if (myRaytraceProgram.IsNull())
1483       {
1484         return safeFailBack ("Failed to initialize ray-trace shader program", theGlContext);
1485       }
1486     }
1487
1488     {
1489       if (!aShaderFolder.IsEmpty())
1490       {
1491         const TCollection_AsciiString aFiles[] = { aShaderFolder + "/RaytraceBase.fs", aShaderFolder + "/RaytraceSmooth.fs", "" };
1492         if (!myPostFSAAShaderSource.LoadFromFiles (aFiles, aPrefixString))
1493         {
1494           return safeFailBack (myPostFSAAShaderSource.ErrorDescription(), theGlContext);
1495         }
1496       }
1497       else
1498       {
1499         const TCollection_AsciiString aSrcShaders[] = { Shaders_RaytraceBase_fs, Shaders_RaytraceSmooth_fs, "" };
1500         myPostFSAAShaderSource.LoadFromStrings (aSrcShaders, aPrefixString);
1501       }
1502
1503       Handle(OpenGl_ShaderObject) aBasicVertShader = initShader (GL_VERTEX_SHADER, aBasicVertShaderSrc, theGlContext);
1504       if (aBasicVertShader.IsNull())
1505       {
1506         return safeFailBack ("Failed to initialize FSAA vertex shader", theGlContext);
1507       }
1508
1509       myPostFSAAShader = initShader (GL_FRAGMENT_SHADER, myPostFSAAShaderSource, theGlContext);
1510       if (myPostFSAAShader.IsNull())
1511       {
1512         aBasicVertShader->Release (theGlContext.operator->());
1513         return safeFailBack ("Failed to initialize FSAA fragment shader", theGlContext);
1514       }
1515
1516       myPostFSAAProgram = initProgram (theGlContext, aBasicVertShader, myPostFSAAShader, "fsaa");
1517       if (myPostFSAAProgram.IsNull())
1518       {
1519         return safeFailBack ("Failed to initialize FSAA shader program", theGlContext);
1520       }
1521     }
1522
1523     {
1524       if (!aShaderFolder.IsEmpty())
1525       {
1526         const TCollection_AsciiString aFiles[] = { aShaderFolder + "/Display.fs", "" };
1527         if (!myOutImageShaderSource.LoadFromFiles (aFiles, aPrefixString))
1528         {
1529           return safeFailBack (myOutImageShaderSource.ErrorDescription(), theGlContext);
1530         }
1531       }
1532       else
1533       {
1534         const TCollection_AsciiString aSrcShaders[] = { Shaders_Display_fs, "" };
1535         myOutImageShaderSource.LoadFromStrings (aSrcShaders, aPrefixString);
1536       }
1537
1538       Handle(OpenGl_ShaderObject) aBasicVertShader = initShader (GL_VERTEX_SHADER, aBasicVertShaderSrc, theGlContext);
1539       if (aBasicVertShader.IsNull())
1540       {
1541         return safeFailBack ("Failed to set vertex shader source", theGlContext);
1542       }
1543
1544       myOutImageShader = initShader (GL_FRAGMENT_SHADER, myOutImageShaderSource, theGlContext);
1545       if (myOutImageShader.IsNull())
1546       {
1547         aBasicVertShader->Release (theGlContext.operator->());
1548         return safeFailBack ("Failed to set display fragment shader source", theGlContext);
1549       }
1550
1551       myOutImageProgram = initProgram (theGlContext, aBasicVertShader, myOutImageShader, "out");
1552       if (myOutImageProgram.IsNull())
1553       {
1554         return safeFailBack ("Failed to initialize display shader program", theGlContext);
1555       }
1556     }
1557   }
1558
1559   if (myRaytraceInitStatus == OpenGl_RT_NONE || aToRebuildShaders)
1560   {
1561     for (Standard_Integer anIndex = 0; anIndex < 2; ++anIndex)
1562     {
1563       Handle(OpenGl_ShaderProgram)& aShaderProgram =
1564         (anIndex == 0) ? myRaytraceProgram : myPostFSAAProgram;
1565
1566       theGlContext->BindProgram (aShaderProgram);
1567
1568       aShaderProgram->SetSampler (theGlContext,
1569         "uSceneMinPointTexture", OpenGl_RT_SceneMinPointTexture);
1570       aShaderProgram->SetSampler (theGlContext,
1571         "uSceneMaxPointTexture", OpenGl_RT_SceneMaxPointTexture);
1572       aShaderProgram->SetSampler (theGlContext,
1573         "uSceneNodeInfoTexture", OpenGl_RT_SceneNodeInfoTexture);
1574       aShaderProgram->SetSampler (theGlContext,
1575         "uGeometryVertexTexture", OpenGl_RT_GeometryVertexTexture);
1576       aShaderProgram->SetSampler (theGlContext,
1577         "uGeometryNormalTexture", OpenGl_RT_GeometryNormalTexture);
1578       aShaderProgram->SetSampler (theGlContext,
1579         "uGeometryTexCrdTexture", OpenGl_RT_GeometryTexCrdTexture);
1580       aShaderProgram->SetSampler (theGlContext,
1581         "uGeometryTriangTexture", OpenGl_RT_GeometryTriangTexture);
1582       aShaderProgram->SetSampler (theGlContext, 
1583         "uSceneTransformTexture", OpenGl_RT_SceneTransformTexture);
1584       aShaderProgram->SetSampler (theGlContext,
1585         "uEnvironmentMapTexture", OpenGl_RT_EnvironmentMapTexture);
1586       aShaderProgram->SetSampler (theGlContext,
1587         "uRaytraceMaterialTexture", OpenGl_RT_RaytraceMaterialTexture);
1588       aShaderProgram->SetSampler (theGlContext,
1589         "uRaytraceLightSrcTexture", OpenGl_RT_RaytraceLightSrcTexture);
1590
1591       if (anIndex == 1)
1592       {
1593         aShaderProgram->SetSampler (theGlContext,
1594           "uFSAAInputTexture", OpenGl_RT_FsaaInputTexture);
1595       }
1596       else
1597       {
1598         aShaderProgram->SetSampler (theGlContext,
1599           "uAccumTexture", OpenGl_RT_PrevAccumTexture);
1600       }
1601
1602       myUniformLocations[anIndex][OpenGl_RT_aPosition] =
1603         aShaderProgram->GetAttributeLocation (theGlContext, "occVertex");
1604
1605       myUniformLocations[anIndex][OpenGl_RT_uOriginLB] =
1606         aShaderProgram->GetUniformLocation (theGlContext, "uOriginLB");
1607       myUniformLocations[anIndex][OpenGl_RT_uOriginRB] =
1608         aShaderProgram->GetUniformLocation (theGlContext, "uOriginRB");
1609       myUniformLocations[anIndex][OpenGl_RT_uOriginLT] =
1610         aShaderProgram->GetUniformLocation (theGlContext, "uOriginLT");
1611       myUniformLocations[anIndex][OpenGl_RT_uOriginRT] =
1612         aShaderProgram->GetUniformLocation (theGlContext, "uOriginRT");
1613       myUniformLocations[anIndex][OpenGl_RT_uDirectLB] =
1614         aShaderProgram->GetUniformLocation (theGlContext, "uDirectLB");
1615       myUniformLocations[anIndex][OpenGl_RT_uDirectRB] =
1616         aShaderProgram->GetUniformLocation (theGlContext, "uDirectRB");
1617       myUniformLocations[anIndex][OpenGl_RT_uDirectLT] =
1618         aShaderProgram->GetUniformLocation (theGlContext, "uDirectLT");
1619       myUniformLocations[anIndex][OpenGl_RT_uDirectRT] =
1620         aShaderProgram->GetUniformLocation (theGlContext, "uDirectRT");
1621       myUniformLocations[anIndex][OpenGl_RT_uViewPrMat] =
1622         aShaderProgram->GetUniformLocation (theGlContext, "uViewMat");
1623       myUniformLocations[anIndex][OpenGl_RT_uUnviewMat] =
1624         aShaderProgram->GetUniformLocation (theGlContext, "uUnviewMat");
1625
1626       myUniformLocations[anIndex][OpenGl_RT_uSceneRad] =
1627         aShaderProgram->GetUniformLocation (theGlContext, "uSceneRadius");
1628       myUniformLocations[anIndex][OpenGl_RT_uSceneEps] =
1629         aShaderProgram->GetUniformLocation (theGlContext, "uSceneEpsilon");
1630       myUniformLocations[anIndex][OpenGl_RT_uLightCount] =
1631         aShaderProgram->GetUniformLocation (theGlContext, "uLightCount");
1632       myUniformLocations[anIndex][OpenGl_RT_uLightAmbnt] =
1633         aShaderProgram->GetUniformLocation (theGlContext, "uGlobalAmbient");
1634
1635       myUniformLocations[anIndex][OpenGl_RT_uOffsetX] =
1636         aShaderProgram->GetUniformLocation (theGlContext, "uOffsetX");
1637       myUniformLocations[anIndex][OpenGl_RT_uOffsetY] =
1638         aShaderProgram->GetUniformLocation (theGlContext, "uOffsetY");
1639       myUniformLocations[anIndex][OpenGl_RT_uSamples] =
1640         aShaderProgram->GetUniformLocation (theGlContext, "uSamples");
1641
1642       myUniformLocations[anIndex][OpenGl_RT_uTexSamplersArray] =
1643         aShaderProgram->GetUniformLocation (theGlContext, "uTextureSamplers");
1644
1645       myUniformLocations[anIndex][OpenGl_RT_uShadowsEnabled] =
1646         aShaderProgram->GetUniformLocation (theGlContext, "uShadowsEnabled");
1647       myUniformLocations[anIndex][OpenGl_RT_uReflectEnabled] =
1648         aShaderProgram->GetUniformLocation (theGlContext, "uReflectEnabled");
1649       myUniformLocations[anIndex][OpenGl_RT_uSphereMapEnabled] =
1650         aShaderProgram->GetUniformLocation (theGlContext, "uSphereMapEnabled");
1651       myUniformLocations[anIndex][OpenGl_RT_uSphereMapForBack] =
1652         aShaderProgram->GetUniformLocation (theGlContext, "uSphereMapForBack");
1653       myUniformLocations[anIndex][OpenGl_RT_uBlockedRngEnabled] =
1654         aShaderProgram->GetUniformLocation (theGlContext, "uBlockedRngEnabled");
1655
1656       myUniformLocations[anIndex][OpenGl_RT_uWinSizeX] =
1657         aShaderProgram->GetUniformLocation (theGlContext, "uWinSizeX");
1658       myUniformLocations[anIndex][OpenGl_RT_uWinSizeY] =
1659         aShaderProgram->GetUniformLocation (theGlContext, "uWinSizeY");
1660
1661       myUniformLocations[anIndex][OpenGl_RT_uAccumSamples] =
1662         aShaderProgram->GetUniformLocation (theGlContext, "uAccumSamples");
1663       myUniformLocations[anIndex][OpenGl_RT_uFrameRndSeed] =
1664         aShaderProgram->GetUniformLocation (theGlContext, "uFrameRndSeed");
1665
1666       myUniformLocations[anIndex][OpenGl_RT_uRenderImage] =
1667         aShaderProgram->GetUniformLocation (theGlContext, "uRenderImage");
1668       myUniformLocations[anIndex][OpenGl_RT_uTilesImage] =
1669         aShaderProgram->GetUniformLocation (theGlContext, "uTilesImage");
1670       myUniformLocations[anIndex][OpenGl_RT_uOffsetImage] =
1671         aShaderProgram->GetUniformLocation (theGlContext, "uOffsetImage");
1672       myUniformLocations[anIndex][OpenGl_RT_uTileSize] =
1673         aShaderProgram->GetUniformLocation (theGlContext, "uTileSize");
1674       myUniformLocations[anIndex][OpenGl_RT_uVarianceScaleFactor] =
1675         aShaderProgram->GetUniformLocation (theGlContext, "uVarianceScaleFactor");
1676
1677       myUniformLocations[anIndex][OpenGl_RT_uBackColorTop] =
1678         aShaderProgram->GetUniformLocation (theGlContext, "uBackColorTop");
1679       myUniformLocations[anIndex][OpenGl_RT_uBackColorBot] =
1680         aShaderProgram->GetUniformLocation (theGlContext, "uBackColorBot");
1681
1682       myUniformLocations[anIndex][OpenGl_RT_uMaxRadiance] =
1683         aShaderProgram->GetUniformLocation (theGlContext, "uMaxRadiance");
1684     }
1685
1686     theGlContext->BindProgram (myOutImageProgram);
1687
1688     myOutImageProgram->SetSampler (theGlContext,
1689       "uInputTexture", OpenGl_RT_PrevAccumTexture);
1690
1691     myOutImageProgram->SetSampler (theGlContext,
1692       "uDepthTexture", OpenGl_RT_RaytraceDepthTexture);
1693
1694     theGlContext->BindProgram (NULL);
1695   }
1696
1697   if (myRaytraceInitStatus != OpenGl_RT_NONE)
1698   {
1699     return myRaytraceInitStatus == OpenGl_RT_INIT;
1700   }
1701
1702   const GLfloat aVertices[] = { -1.f, -1.f,  0.f,
1703                                 -1.f,  1.f,  0.f,
1704                                  1.f,  1.f,  0.f,
1705                                  1.f,  1.f,  0.f,
1706                                  1.f, -1.f,  0.f,
1707                                 -1.f, -1.f,  0.f };
1708
1709   myRaytraceScreenQuad.Init (theGlContext, 3, 6, aVertices);
1710
1711   myRaytraceInitStatus = OpenGl_RT_INIT; // initialized in normal way
1712
1713   return Standard_True;
1714 }
1715
1716 // =======================================================================
1717 // function : nullifyResource
1718 // purpose  : Releases OpenGL resource
1719 // =======================================================================
1720 template <class T>
1721 inline void nullifyResource (const Handle(OpenGl_Context)& theGlContext, Handle(T)& theResource)
1722 {
1723   if (!theResource.IsNull())
1724   {
1725     theResource->Release (theGlContext.get());
1726     theResource.Nullify();
1727   }
1728 }
1729
1730 // =======================================================================
1731 // function : releaseRaytraceResources
1732 // purpose  : Releases OpenGL/GLSL shader programs
1733 // =======================================================================
1734 void OpenGl_View::releaseRaytraceResources (const Handle(OpenGl_Context)& theGlContext, const Standard_Boolean theToRebuild)
1735 {
1736   // release shader resources
1737   nullifyResource (theGlContext, myRaytraceShader);
1738   nullifyResource (theGlContext, myPostFSAAShader);
1739
1740   nullifyResource (theGlContext, myRaytraceProgram);
1741   nullifyResource (theGlContext, myPostFSAAProgram);
1742   nullifyResource (theGlContext, myOutImageProgram);
1743
1744   if (!theToRebuild) // complete release
1745   {
1746     myRaytraceFBO1[0]->Release (theGlContext.get());
1747     myRaytraceFBO1[1]->Release (theGlContext.get());
1748     myRaytraceFBO2[0]->Release (theGlContext.get());
1749     myRaytraceFBO2[1]->Release (theGlContext.get());
1750
1751     nullifyResource (theGlContext, myRaytraceOutputTexture[0]);
1752     nullifyResource (theGlContext, myRaytraceOutputTexture[1]);
1753
1754     nullifyResource (theGlContext, myRaytraceTileOffsetsTexture[0]);
1755     nullifyResource (theGlContext, myRaytraceTileOffsetsTexture[1]);
1756     nullifyResource (theGlContext, myRaytraceVisualErrorTexture[0]);
1757     nullifyResource (theGlContext, myRaytraceVisualErrorTexture[1]);
1758     nullifyResource (theGlContext, myRaytraceTileSamplesTexture[0]);
1759     nullifyResource (theGlContext, myRaytraceTileSamplesTexture[1]);
1760
1761     nullifyResource (theGlContext, mySceneNodeInfoTexture);
1762     nullifyResource (theGlContext, mySceneMinPointTexture);
1763     nullifyResource (theGlContext, mySceneMaxPointTexture);
1764
1765     nullifyResource (theGlContext, myGeometryVertexTexture);
1766     nullifyResource (theGlContext, myGeometryNormalTexture);
1767     nullifyResource (theGlContext, myGeometryTexCrdTexture);
1768     nullifyResource (theGlContext, myGeometryTriangTexture);
1769     nullifyResource (theGlContext, mySceneTransformTexture);
1770
1771     nullifyResource (theGlContext, myRaytraceLightSrcTexture);
1772     nullifyResource (theGlContext, myRaytraceMaterialTexture);
1773
1774     myRaytraceGeometry.ReleaseResources (theGlContext);
1775
1776     if (myRaytraceScreenQuad.IsValid ())
1777     {
1778       myRaytraceScreenQuad.Release (theGlContext.get());
1779     }
1780   }
1781 }
1782
1783 // =======================================================================
1784 // function : updateRaytraceBuffers
1785 // purpose  : Updates auxiliary OpenGL frame buffers.
1786 // =======================================================================
1787 Standard_Boolean OpenGl_View::updateRaytraceBuffers (const Standard_Integer        theSizeX,
1788                                                      const Standard_Integer        theSizeY,
1789                                                      const Handle(OpenGl_Context)& theGlContext)
1790 {
1791   // Auxiliary buffers are not used
1792   if (!myRaytraceParameters.GlobalIllumination && !myRenderParams.IsAntialiasingEnabled)
1793   {
1794     myRaytraceFBO1[0]->Release (theGlContext.operator->());
1795     myRaytraceFBO2[0]->Release (theGlContext.operator->());
1796     myRaytraceFBO1[1]->Release (theGlContext.operator->());
1797     myRaytraceFBO2[1]->Release (theGlContext.operator->());
1798
1799     return Standard_True;
1800   }
1801
1802   if (myRaytraceParameters.AdaptiveScreenSampling)
1803   {
1804     Graphic3d_Vec2i aMaxViewport = myTileSampler.OffsetTilesViewportMax().cwiseMax (Graphic3d_Vec2i (theSizeX, theSizeY));
1805     myRaytraceFBO1[0]->InitLazy (theGlContext, aMaxViewport.x(), aMaxViewport.y(), GL_RGBA32F, myFboDepthFormat);
1806     myRaytraceFBO2[0]->InitLazy (theGlContext, aMaxViewport.x(), aMaxViewport.y(), GL_RGBA32F, myFboDepthFormat);
1807     if (myRaytraceFBO1[1]->IsValid()) // second FBO not needed
1808     {
1809       myRaytraceFBO1[1]->Release (theGlContext.operator->());
1810       myRaytraceFBO2[1]->Release (theGlContext.operator->());
1811     }
1812   }
1813
1814   for (int aViewIter = 0; aViewIter < 2; ++aViewIter)
1815   {
1816     if (myRaytraceTileOffsetsTexture[aViewIter].IsNull())
1817     {
1818       myRaytraceOutputTexture[aViewIter] = new OpenGl_Texture();
1819       myRaytraceVisualErrorTexture[aViewIter] = new OpenGl_Texture();
1820       myRaytraceTileSamplesTexture[aViewIter] = new OpenGl_Texture();
1821       myRaytraceTileOffsetsTexture[aViewIter] = new OpenGl_Texture();
1822     }
1823
1824     if (aViewIter == 1
1825      && myCamera->ProjectionType() != Graphic3d_Camera::Projection_Stereo)
1826     {
1827       myRaytraceFBO1[1]->Release (theGlContext.operator->());
1828       myRaytraceFBO2[1]->Release (theGlContext.operator->());
1829       myRaytraceOutputTexture[1]->Release (theGlContext.operator->());
1830       myRaytraceVisualErrorTexture[1]->Release (theGlContext.operator->());
1831       myRaytraceTileOffsetsTexture[1]->Release (theGlContext.operator->());
1832       continue;
1833     }
1834
1835     if (myRaytraceParameters.AdaptiveScreenSampling)
1836     {
1837       if (myRaytraceOutputTexture[aViewIter]->SizeX() / 3 == theSizeX
1838        && myRaytraceOutputTexture[aViewIter]->SizeY() / 2 == theSizeY
1839        && myRaytraceVisualErrorTexture[aViewIter]->SizeX() == myTileSampler.NbTilesX()
1840        && myRaytraceVisualErrorTexture[aViewIter]->SizeY() == myTileSampler.NbTilesY())
1841       {
1842         if (myRaytraceParameters.AdaptiveScreenSamplingAtomic)
1843         {
1844           continue; // offsets texture is dynamically resized
1845         }
1846         else if (myRaytraceTileSamplesTexture[aViewIter]->SizeX() == myTileSampler.NbTilesX()
1847               && myRaytraceTileSamplesTexture[aViewIter]->SizeY() == myTileSampler.NbTilesY())
1848         {
1849           continue;
1850         }
1851       }
1852
1853       myAccumFrames = 0;
1854
1855       // Due to limitations of OpenGL image load-store extension
1856       // atomic operations are supported only for single-channel
1857       // images, so we define GL_R32F image. It is used as array
1858       // of 6D floating point vectors:
1859       // 0 - R color channel
1860       // 1 - G color channel
1861       // 2 - B color channel
1862       // 3 - hit time transformed into OpenGL NDC space
1863       // 4 - luminance accumulated for odd samples only
1864       myRaytraceOutputTexture[aViewIter]->InitRectangle (theGlContext, theSizeX * 3, theSizeY * 2, OpenGl_TextureFormat::Create<GLfloat, 1>());
1865
1866       // workaround for some NVIDIA drivers
1867       myRaytraceVisualErrorTexture[aViewIter]->Release (theGlContext.operator->());
1868       myRaytraceTileSamplesTexture[aViewIter]->Release (theGlContext.operator->());
1869       myRaytraceVisualErrorTexture[aViewIter]->Init (theGlContext, GL_R32I, GL_RED_INTEGER, GL_INT,
1870                                                      myTileSampler.NbTilesX(), myTileSampler.NbTilesY(), Graphic3d_TOT_2D);
1871       if (!myRaytraceParameters.AdaptiveScreenSamplingAtomic)
1872       {
1873         myRaytraceTileSamplesTexture[aViewIter]->Init (theGlContext, GL_R32I, GL_RED_INTEGER, GL_INT,
1874                                                        myTileSampler.NbTilesX(), myTileSampler.NbTilesY(), Graphic3d_TOT_2D);
1875       }
1876     }
1877     else // non-adaptive mode
1878     {
1879       if (myRaytraceFBO1[aViewIter]->GetSizeX() != theSizeX
1880        || myRaytraceFBO1[aViewIter]->GetSizeY() != theSizeY)
1881       {
1882         myAccumFrames = 0; // accumulation should be restarted
1883       }
1884
1885       myRaytraceFBO1[aViewIter]->InitLazy (theGlContext, theSizeX, theSizeY, GL_RGBA32F, myFboDepthFormat);
1886       myRaytraceFBO2[aViewIter]->InitLazy (theGlContext, theSizeX, theSizeY, GL_RGBA32F, myFboDepthFormat);
1887     }
1888   }
1889   return Standard_True;
1890 }
1891
1892 // =======================================================================
1893 // function : updateCamera
1894 // purpose  : Generates viewing rays for corners of screen quad
1895 // =======================================================================
1896 void OpenGl_View::updateCamera (const OpenGl_Mat4& theOrientation,
1897                                 const OpenGl_Mat4& theViewMapping,
1898                                 OpenGl_Vec3*       theOrigins,
1899                                 OpenGl_Vec3*       theDirects,
1900                                 OpenGl_Mat4&       theViewPr,
1901                                 OpenGl_Mat4&       theUnview)
1902 {
1903   // compute view-projection matrix
1904   theViewPr = theViewMapping * theOrientation;
1905
1906   // compute inverse view-projection matrix
1907   theViewPr.Inverted (theUnview);
1908
1909   Standard_Integer aOriginIndex = 0;
1910   Standard_Integer aDirectIndex = 0;
1911
1912   for (Standard_Integer aY = -1; aY <= 1; aY += 2)
1913   {
1914     for (Standard_Integer aX = -1; aX <= 1; aX += 2)
1915     {
1916       OpenGl_Vec4 aOrigin (GLfloat(aX),
1917                            GLfloat(aY),
1918                            -1.0f,
1919                            1.0f);
1920
1921       aOrigin = theUnview * aOrigin;
1922
1923       aOrigin.x() = aOrigin.x() / aOrigin.w();
1924       aOrigin.y() = aOrigin.y() / aOrigin.w();
1925       aOrigin.z() = aOrigin.z() / aOrigin.w();
1926
1927       OpenGl_Vec4 aDirect (GLfloat(aX),
1928                            GLfloat(aY),
1929                            1.0f,
1930                            1.0f);
1931
1932       aDirect = theUnview * aDirect;
1933
1934       aDirect.x() = aDirect.x() / aDirect.w();
1935       aDirect.y() = aDirect.y() / aDirect.w();
1936       aDirect.z() = aDirect.z() / aDirect.w();
1937
1938       aDirect = aDirect - aOrigin;
1939
1940       theOrigins[aOriginIndex++] = OpenGl_Vec3 (static_cast<GLfloat> (aOrigin.x()),
1941                                                 static_cast<GLfloat> (aOrigin.y()),
1942                                                 static_cast<GLfloat> (aOrigin.z()));
1943
1944       theDirects[aDirectIndex++] = OpenGl_Vec3 (static_cast<GLfloat> (aDirect.x()),
1945                                                 static_cast<GLfloat> (aDirect.y()),
1946                                                 static_cast<GLfloat> (aDirect.z()));
1947     }
1948   }
1949 }
1950
1951 // =======================================================================
1952 // function : updatePerspCameraPT
1953 // purpose  : Generates viewing rays (path tracing, perspective camera)
1954 // =======================================================================
1955 void OpenGl_View::updatePerspCameraPT (const OpenGl_Mat4&           theOrientation,
1956                                        const OpenGl_Mat4&           theViewMapping,
1957                                        Graphic3d_Camera::Projection theProjection,
1958                                        OpenGl_Mat4&                 theViewPr,
1959                                        OpenGl_Mat4&                 theUnview,
1960                                        const int                    theWinSizeX,
1961                                        const int                    theWinSizeY)
1962 {
1963   // compute view-projection matrix
1964   theViewPr = theViewMapping * theOrientation;
1965
1966   // compute inverse view-projection matrix
1967   theViewPr.Inverted(theUnview);
1968   
1969   // get camera stereo params
1970   float anIOD = myCamera->GetIODType() == Graphic3d_Camera::IODType_Relative
1971     ? static_cast<float> (myCamera->IOD() * myCamera->Distance())
1972     : static_cast<float> (myCamera->IOD());
1973
1974   float aZFocus = myCamera->ZFocusType() == Graphic3d_Camera::FocusType_Relative
1975     ? static_cast<float> (myCamera->ZFocus() * myCamera->Distance())
1976     : static_cast<float> (myCamera->ZFocus());
1977
1978   // get camera view vectors
1979   const gp_Pnt anOrig = myCamera->Eye();
1980
1981   myEyeOrig = OpenGl_Vec3 (static_cast<float> (anOrig.X()),
1982                            static_cast<float> (anOrig.Y()),
1983                            static_cast<float> (anOrig.Z()));
1984
1985   const gp_Dir aView = myCamera->Direction();
1986
1987   OpenGl_Vec3 anEyeViewMono = OpenGl_Vec3 (static_cast<float> (aView.X()),
1988                                            static_cast<float> (aView.Y()),
1989                                            static_cast<float> (aView.Z()));
1990
1991   const gp_Dir anUp = myCamera->Up();
1992
1993   myEyeVert = OpenGl_Vec3 (static_cast<float> (anUp.X()),
1994                            static_cast<float> (anUp.Y()),
1995                            static_cast<float> (anUp.Z()));
1996
1997   myEyeSide = OpenGl_Vec3::Cross (anEyeViewMono, myEyeVert);
1998
1999   const double aScaleY = tan (myCamera->FOVy() / 360 * M_PI);
2000   const double aScaleX = theWinSizeX * aScaleY / theWinSizeY;
2001  
2002   myEyeSize = OpenGl_Vec2 (static_cast<float> (aScaleX),
2003                            static_cast<float> (aScaleY));
2004
2005   if (theProjection == Graphic3d_Camera::Projection_Perspective)
2006   {
2007     myEyeView = anEyeViewMono;
2008   }
2009   else // stereo camera
2010   {
2011     // compute z-focus point
2012     OpenGl_Vec3 aZFocusPoint = myEyeOrig + anEyeViewMono * aZFocus;
2013
2014     // compute stereo camera shift
2015     float aDx = theProjection == Graphic3d_Camera::Projection_MonoRightEye ? 0.5f * anIOD : -0.5f * anIOD;
2016     myEyeOrig += myEyeSide.Normalized() * aDx;
2017
2018     // estimate new camera direction vector and correct its length
2019     myEyeView = (aZFocusPoint - myEyeOrig).Normalized();
2020     myEyeView *= 1.f / anEyeViewMono.Dot (myEyeView);
2021   }
2022 }
2023
2024 // =======================================================================
2025 // function : uploadRaytraceData
2026 // purpose  : Uploads ray-trace data to the GPU
2027 // =======================================================================
2028 Standard_Boolean OpenGl_View::uploadRaytraceData (const Handle(OpenGl_Context)& theGlContext)
2029 {
2030   if (!theGlContext->IsGlGreaterEqual (3, 1))
2031   {
2032 #ifdef RAY_TRACE_PRINT_INFO
2033     std::cout << "Error: OpenGL version is less than 3.1" << std::endl;
2034 #endif
2035     return Standard_False;
2036   }
2037
2038   myAccumFrames = 0; // accumulation should be restarted
2039
2040   /////////////////////////////////////////////////////////////////////////////
2041   // Prepare OpenGL textures
2042
2043   if (theGlContext->arbTexBindless != NULL)
2044   {
2045     // If OpenGL driver supports bindless textures we need
2046     // to get unique 64- bit handles for using on the GPU
2047     if (!myRaytraceGeometry.UpdateTextureHandles (theGlContext))
2048     {
2049 #ifdef RAY_TRACE_PRINT_INFO
2050       std::cout << "Error: Failed to get OpenGL texture handles" << std::endl;
2051 #endif
2052       return Standard_False;
2053     }
2054   }
2055
2056   /////////////////////////////////////////////////////////////////////////////
2057   // Create OpenGL BVH buffers
2058
2059   if (mySceneNodeInfoTexture.IsNull()) // create scene BVH buffers
2060   {
2061     mySceneNodeInfoTexture  = new OpenGl_TextureBufferArb;
2062     mySceneMinPointTexture  = new OpenGl_TextureBufferArb;
2063     mySceneMaxPointTexture  = new OpenGl_TextureBufferArb;
2064     mySceneTransformTexture = new OpenGl_TextureBufferArb;
2065
2066     if (!mySceneNodeInfoTexture->Create  (theGlContext)
2067      || !mySceneMinPointTexture->Create  (theGlContext)
2068      || !mySceneMaxPointTexture->Create  (theGlContext)
2069      || !mySceneTransformTexture->Create (theGlContext))
2070     {
2071 #ifdef RAY_TRACE_PRINT_INFO
2072       std::cout << "Error: Failed to create scene BVH buffers" << std::endl;
2073 #endif
2074       return Standard_False;
2075     }
2076   }
2077
2078   if (myGeometryVertexTexture.IsNull()) // create geometry buffers
2079   {
2080     myGeometryVertexTexture = new OpenGl_TextureBufferArb;
2081     myGeometryNormalTexture = new OpenGl_TextureBufferArb;
2082     myGeometryTexCrdTexture = new OpenGl_TextureBufferArb;
2083     myGeometryTriangTexture = new OpenGl_TextureBufferArb;
2084
2085     if (!myGeometryVertexTexture->Create (theGlContext)
2086      || !myGeometryNormalTexture->Create (theGlContext)
2087      || !myGeometryTexCrdTexture->Create (theGlContext)
2088      || !myGeometryTriangTexture->Create (theGlContext))
2089     {
2090 #ifdef RAY_TRACE_PRINT_INFO
2091       std::cout << "Error: Failed to create buffers for triangulation data" << std::endl;
2092 #endif
2093       return Standard_False;
2094     }
2095   }
2096
2097   if (myRaytraceMaterialTexture.IsNull()) // create material buffer
2098   {
2099     myRaytraceMaterialTexture = new OpenGl_TextureBufferArb;
2100
2101     if (!myRaytraceMaterialTexture->Create (theGlContext))
2102     {
2103 #ifdef RAY_TRACE_PRINT_INFO
2104       std::cout << "Error: Failed to create buffers for material data" << std::endl;
2105 #endif
2106       return Standard_False;
2107     }
2108   }
2109   
2110   /////////////////////////////////////////////////////////////////////////////
2111   // Write transform buffer
2112
2113   BVH_Mat4f* aNodeTransforms = new BVH_Mat4f[myRaytraceGeometry.Size()];
2114
2115   bool aResult = true;
2116
2117   for (Standard_Integer anElemIndex = 0; anElemIndex < myRaytraceGeometry.Size(); ++anElemIndex)
2118   {
2119     OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
2120       myRaytraceGeometry.Objects().ChangeValue (anElemIndex).operator->());
2121
2122     const BVH_Transform<Standard_ShortReal, 4>* aTransform = dynamic_cast<const BVH_Transform<Standard_ShortReal, 4>* > (aTriangleSet->Properties().get());
2123     Standard_ASSERT_RETURN (aTransform != NULL,
2124       "OpenGl_TriangleSet does not contain transform", Standard_False);
2125
2126     aNodeTransforms[anElemIndex] = aTransform->Inversed();
2127   }
2128
2129   aResult &= mySceneTransformTexture->Init (theGlContext, 4,
2130     myRaytraceGeometry.Size() * 4, reinterpret_cast<const GLfloat*> (aNodeTransforms));
2131
2132   delete [] aNodeTransforms;
2133
2134   /////////////////////////////////////////////////////////////////////////////
2135   // Write geometry and bottom-level BVH buffers
2136
2137   Standard_Size aTotalVerticesNb = 0;
2138   Standard_Size aTotalElementsNb = 0;
2139   Standard_Size aTotalBVHNodesNb = 0;
2140
2141   for (Standard_Integer anElemIndex = 0; anElemIndex < myRaytraceGeometry.Size(); ++anElemIndex)
2142   {
2143     OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
2144       myRaytraceGeometry.Objects().ChangeValue (anElemIndex).operator->());
2145
2146     Standard_ASSERT_RETURN (aTriangleSet != NULL,
2147       "Error: Failed to get triangulation of OpenGL element", Standard_False);
2148
2149     aTotalVerticesNb += aTriangleSet->Vertices.size();
2150     aTotalElementsNb += aTriangleSet->Elements.size();
2151
2152     Standard_ASSERT_RETURN (!aTriangleSet->QuadBVH().IsNull(),
2153       "Error: Failed to get bottom-level BVH of OpenGL element", Standard_False);
2154
2155     aTotalBVHNodesNb += aTriangleSet->QuadBVH()->NodeInfoBuffer().size();
2156   }
2157
2158   aTotalBVHNodesNb += myRaytraceGeometry.QuadBVH()->NodeInfoBuffer().size();
2159
2160   if (aTotalBVHNodesNb != 0)
2161   {
2162     aResult &= mySceneNodeInfoTexture->Init (
2163       theGlContext, 4, GLsizei (aTotalBVHNodesNb), static_cast<const GLuint*>  (NULL));
2164     aResult &= mySceneMinPointTexture->Init (
2165       theGlContext, 3, GLsizei (aTotalBVHNodesNb), static_cast<const GLfloat*> (NULL));
2166     aResult &= mySceneMaxPointTexture->Init (
2167       theGlContext, 3, GLsizei (aTotalBVHNodesNb), static_cast<const GLfloat*> (NULL));
2168   }
2169
2170   if (!aResult)
2171   {
2172 #ifdef RAY_TRACE_PRINT_INFO
2173     std::cout << "Error: Failed to upload buffers for bottom-level scene BVH" << std::endl;
2174 #endif
2175     return Standard_False;
2176   }
2177
2178   if (aTotalElementsNb != 0)
2179   {
2180     aResult &= myGeometryTriangTexture->Init (
2181       theGlContext, 4, GLsizei (aTotalElementsNb), static_cast<const GLuint*> (NULL));
2182   }
2183
2184   if (aTotalVerticesNb != 0)
2185   {
2186     aResult &= myGeometryVertexTexture->Init (
2187       theGlContext, 3, GLsizei (aTotalVerticesNb), static_cast<const GLfloat*> (NULL));
2188     aResult &= myGeometryNormalTexture->Init (
2189       theGlContext, 3, GLsizei (aTotalVerticesNb), static_cast<const GLfloat*> (NULL));
2190     aResult &= myGeometryTexCrdTexture->Init (
2191       theGlContext, 2, GLsizei (aTotalVerticesNb), static_cast<const GLfloat*> (NULL));
2192   }
2193
2194   if (!aResult)
2195   {
2196 #ifdef RAY_TRACE_PRINT_INFO
2197     std::cout << "Error: Failed to upload buffers for scene geometry" << std::endl;
2198 #endif
2199     return Standard_False;
2200   }
2201
2202   const QuadBvhHandle& aBVH = myRaytraceGeometry.QuadBVH();
2203
2204   if (aBVH->Length() > 0)
2205   {
2206     aResult &= mySceneNodeInfoTexture->SubData (theGlContext, 0, aBVH->Length(),
2207       reinterpret_cast<const GLuint*> (&aBVH->NodeInfoBuffer().front()));
2208     aResult &= mySceneMinPointTexture->SubData (theGlContext, 0, aBVH->Length(),
2209       reinterpret_cast<const GLfloat*> (&aBVH->MinPointBuffer().front()));
2210     aResult &= mySceneMaxPointTexture->SubData (theGlContext, 0, aBVH->Length(),
2211       reinterpret_cast<const GLfloat*> (&aBVH->MaxPointBuffer().front()));
2212   }
2213
2214   for (Standard_Integer aNodeIdx = 0; aNodeIdx < aBVH->Length(); ++aNodeIdx)
2215   {
2216     if (!aBVH->IsOuter (aNodeIdx))
2217       continue;
2218
2219     OpenGl_TriangleSet* aTriangleSet = myRaytraceGeometry.TriangleSet (aNodeIdx);
2220
2221     Standard_ASSERT_RETURN (aTriangleSet != NULL,
2222       "Error: Failed to get triangulation of OpenGL element", Standard_False);
2223
2224     Standard_Integer aBVHOffset = myRaytraceGeometry.AccelerationOffset (aNodeIdx);
2225
2226     Standard_ASSERT_RETURN (aBVHOffset != OpenGl_RaytraceGeometry::INVALID_OFFSET,
2227       "Error: Failed to get offset for bottom-level BVH", Standard_False);
2228
2229     const Standard_Integer aBvhBuffersSize = aTriangleSet->QuadBVH()->Length();
2230
2231     if (aBvhBuffersSize != 0)
2232     {
2233       aResult &= mySceneNodeInfoTexture->SubData (theGlContext, aBVHOffset, aBvhBuffersSize,
2234         reinterpret_cast<const GLuint*> (&aTriangleSet->QuadBVH()->NodeInfoBuffer().front()));
2235       aResult &= mySceneMinPointTexture->SubData (theGlContext, aBVHOffset, aBvhBuffersSize,
2236         reinterpret_cast<const GLfloat*> (&aTriangleSet->QuadBVH()->MinPointBuffer().front()));
2237       aResult &= mySceneMaxPointTexture->SubData (theGlContext, aBVHOffset, aBvhBuffersSize,
2238         reinterpret_cast<const GLfloat*> (&aTriangleSet->QuadBVH()->MaxPointBuffer().front()));
2239
2240       if (!aResult)
2241       {
2242 #ifdef RAY_TRACE_PRINT_INFO
2243         std::cout << "Error: Failed to upload buffers for bottom-level scene BVHs" << std::endl;
2244 #endif
2245         return Standard_False;
2246       }
2247     }
2248
2249     const Standard_Integer aVerticesOffset = myRaytraceGeometry.VerticesOffset (aNodeIdx);
2250
2251     Standard_ASSERT_RETURN (aVerticesOffset != OpenGl_RaytraceGeometry::INVALID_OFFSET,
2252       "Error: Failed to get offset for triangulation vertices of OpenGL element", Standard_False);
2253
2254     if (!aTriangleSet->Vertices.empty())
2255     {
2256       aResult &= myGeometryNormalTexture->SubData (theGlContext, aVerticesOffset,
2257         GLsizei (aTriangleSet->Normals.size()), reinterpret_cast<const GLfloat*> (&aTriangleSet->Normals.front()));
2258       aResult &= myGeometryTexCrdTexture->SubData (theGlContext, aVerticesOffset,
2259         GLsizei (aTriangleSet->TexCrds.size()), reinterpret_cast<const GLfloat*> (&aTriangleSet->TexCrds.front()));
2260       aResult &= myGeometryVertexTexture->SubData (theGlContext, aVerticesOffset,
2261         GLsizei (aTriangleSet->Vertices.size()), reinterpret_cast<const GLfloat*> (&aTriangleSet->Vertices.front()));
2262     }
2263
2264     const Standard_Integer anElementsOffset = myRaytraceGeometry.ElementsOffset (aNodeIdx);
2265
2266     Standard_ASSERT_RETURN (anElementsOffset != OpenGl_RaytraceGeometry::INVALID_OFFSET,
2267       "Error: Failed to get offset for triangulation elements of OpenGL element", Standard_False);
2268
2269     if (!aTriangleSet->Elements.empty())
2270     {
2271       aResult &= myGeometryTriangTexture->SubData (theGlContext, anElementsOffset, GLsizei (aTriangleSet->Elements.size()),
2272                                                    reinterpret_cast<const GLuint*> (&aTriangleSet->Elements.front()));
2273     }
2274
2275     if (!aResult)
2276     {
2277 #ifdef RAY_TRACE_PRINT_INFO
2278       std::cout << "Error: Failed to upload triangulation buffers for OpenGL element" << std::endl;
2279 #endif
2280       return Standard_False;
2281     }
2282   }
2283
2284   /////////////////////////////////////////////////////////////////////////////
2285   // Write material buffer
2286
2287   if (myRaytraceGeometry.Materials.size() != 0)
2288   {
2289     aResult &= myRaytraceMaterialTexture->Init (theGlContext, 4,
2290       GLsizei (myRaytraceGeometry.Materials.size() * 19), myRaytraceGeometry.Materials.front().Packed());
2291
2292     if (!aResult)
2293     {
2294 #ifdef RAY_TRACE_PRINT_INFO
2295       std::cout << "Error: Failed to upload material buffer" << std::endl;
2296 #endif
2297       return Standard_False;
2298     }
2299   }
2300
2301   myIsRaytraceDataValid = myRaytraceGeometry.Objects().Size() != 0;
2302
2303 #ifdef RAY_TRACE_PRINT_INFO
2304
2305   Standard_ShortReal aMemTrgUsed = 0.f;
2306   Standard_ShortReal aMemBvhUsed = 0.f;
2307
2308   for (Standard_Integer anElemIdx = 0; anElemIdx < myRaytraceGeometry.Size(); ++anElemIdx)
2309   {
2310     OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (myRaytraceGeometry.Objects()(anElemIdx).get());
2311
2312     aMemTrgUsed += static_cast<Standard_ShortReal> (
2313       aTriangleSet->Vertices.size() * sizeof (BVH_Vec3f));
2314     aMemTrgUsed += static_cast<Standard_ShortReal> (
2315       aTriangleSet->Normals.size() * sizeof (BVH_Vec3f));
2316     aMemTrgUsed += static_cast<Standard_ShortReal> (
2317       aTriangleSet->TexCrds.size() * sizeof (BVH_Vec2f));
2318     aMemTrgUsed += static_cast<Standard_ShortReal> (
2319       aTriangleSet->Elements.size() * sizeof (BVH_Vec4i));
2320
2321     aMemBvhUsed += static_cast<Standard_ShortReal> (
2322       aTriangleSet->QuadBVH()->NodeInfoBuffer().size() * sizeof (BVH_Vec4i));
2323     aMemBvhUsed += static_cast<Standard_ShortReal> (
2324       aTriangleSet->QuadBVH()->MinPointBuffer().size() * sizeof (BVH_Vec3f));
2325     aMemBvhUsed += static_cast<Standard_ShortReal> (
2326       aTriangleSet->QuadBVH()->MaxPointBuffer().size() * sizeof (BVH_Vec3f));
2327   }
2328
2329   aMemBvhUsed += static_cast<Standard_ShortReal> (
2330     myRaytraceGeometry.QuadBVH()->NodeInfoBuffer().size() * sizeof (BVH_Vec4i));
2331   aMemBvhUsed += static_cast<Standard_ShortReal> (
2332     myRaytraceGeometry.QuadBVH()->MinPointBuffer().size() * sizeof (BVH_Vec3f));
2333   aMemBvhUsed += static_cast<Standard_ShortReal> (
2334     myRaytraceGeometry.QuadBVH()->MaxPointBuffer().size() * sizeof (BVH_Vec3f));
2335
2336   std::cout << "GPU Memory Used (Mb):\n"
2337     << "\tFor mesh: " << aMemTrgUsed / 1048576 << "\n"
2338     << "\tFor BVHs: " << aMemBvhUsed / 1048576 << "\n";
2339
2340 #endif
2341
2342   return aResult;
2343 }
2344
2345 // =======================================================================
2346 // function : updateRaytraceLightSources
2347 // purpose  : Updates 3D scene light sources for ray-tracing
2348 // =======================================================================
2349 Standard_Boolean OpenGl_View::updateRaytraceLightSources (const OpenGl_Mat4& theInvModelView, const Handle(OpenGl_Context)& theGlContext)
2350 {
2351   std::vector<Handle(Graphic3d_CLight)> aLightSources;
2352   myRaytraceGeometry.Ambient = BVH_Vec4f (0.f, 0.f, 0.f, 0.f);
2353   if (myShadingModel != Graphic3d_TOSM_UNLIT
2354   && !myLights.IsNull())
2355   {
2356     const Graphic3d_Vec4& anAmbient = myLights->AmbientColor();
2357     myRaytraceGeometry.Ambient = BVH_Vec4f (anAmbient.r(), anAmbient.g(), anAmbient.b(), 0.0f);
2358
2359     // move positional light sources at the front of the list
2360     aLightSources.reserve (myLights->Extent());
2361     for (Graphic3d_LightSet::Iterator aLightIter (myLights, Graphic3d_LightSet::IterationFilter_ExcludeDisabledAndAmbient);
2362          aLightIter.More(); aLightIter.Next())
2363     {
2364       const Graphic3d_CLight& aLight = *aLightIter.Value();
2365       if (aLight.Type() != Graphic3d_TOLS_DIRECTIONAL)
2366       {
2367         aLightSources.push_back (aLightIter.Value());
2368       }
2369     }
2370
2371     for (Graphic3d_LightSet::Iterator aLightIter (myLights, Graphic3d_LightSet::IterationFilter_ExcludeDisabledAndAmbient);
2372          aLightIter.More(); aLightIter.Next())
2373     {
2374       if (aLightIter.Value()->Type() == Graphic3d_TOLS_DIRECTIONAL)
2375       {
2376         aLightSources.push_back (aLightIter.Value());
2377       }
2378     }
2379   }
2380
2381   // get number of 'real' (not ambient) light sources
2382   const size_t aNbLights = aLightSources.size();
2383   Standard_Boolean wasUpdated = myRaytraceGeometry.Sources.size () != aNbLights;
2384   if (wasUpdated)
2385   {
2386     myRaytraceGeometry.Sources.resize (aNbLights);
2387   }
2388
2389   for (size_t aLightIdx = 0, aRealIdx = 0; aLightIdx < aLightSources.size(); ++aLightIdx)
2390   {
2391     const Graphic3d_CLight& aLight = *aLightSources[aLightIdx];
2392     const Graphic3d_Vec4& aLightColor = aLight.PackedColor();
2393     BVH_Vec4f aEmission  (aLightColor.r() * aLight.Intensity(),
2394                           aLightColor.g() * aLight.Intensity(),
2395                           aLightColor.b() * aLight.Intensity(),
2396                           1.0f);
2397
2398     BVH_Vec4f aPosition (-aLight.PackedDirection().x(),
2399                          -aLight.PackedDirection().y(),
2400                          -aLight.PackedDirection().z(),
2401                          0.0f);
2402
2403     if (aLight.Type() != Graphic3d_TOLS_DIRECTIONAL)
2404     {
2405       aPosition = BVH_Vec4f (static_cast<float>(aLight.Position().X()),
2406                              static_cast<float>(aLight.Position().Y()),
2407                              static_cast<float>(aLight.Position().Z()),
2408                              1.0f);
2409
2410       // store smoothing radius in W-component
2411       aEmission.w() = Max (aLight.Smoothness(), 0.f);
2412     }
2413     else
2414     {
2415       // store cosine of smoothing angle in W-component
2416       aEmission.w() = cosf (Min (Max (aLight.Smoothness(), 0.f), static_cast<Standard_ShortReal> (M_PI / 2.0)));
2417     }
2418
2419     if (aLight.IsHeadlight())
2420     {
2421       aPosition = theInvModelView * aPosition;
2422     }
2423
2424     for (int aK = 0; aK < 4; ++aK)
2425     {
2426       wasUpdated |= (aEmission[aK] != myRaytraceGeometry.Sources[aRealIdx].Emission[aK])
2427                  || (aPosition[aK] != myRaytraceGeometry.Sources[aRealIdx].Position[aK]);
2428     }
2429
2430     if (wasUpdated)
2431     {
2432       myRaytraceGeometry.Sources[aRealIdx] = OpenGl_RaytraceLight (aEmission, aPosition);
2433     }
2434
2435     ++aRealIdx;
2436   }
2437
2438   if (myRaytraceLightSrcTexture.IsNull()) // create light source buffer
2439   {
2440     myRaytraceLightSrcTexture = new OpenGl_TextureBufferArb;
2441   }
2442
2443   if (myRaytraceGeometry.Sources.size() != 0 && wasUpdated)
2444   {
2445     const GLfloat* aDataPtr = myRaytraceGeometry.Sources.front().Packed();
2446     if (!myRaytraceLightSrcTexture->Init (theGlContext, 4, GLsizei (myRaytraceGeometry.Sources.size() * 2), aDataPtr))
2447     {
2448 #ifdef RAY_TRACE_PRINT_INFO
2449       std::cout << "Error: Failed to upload light source buffer" << std::endl;
2450 #endif
2451       return Standard_False;
2452     }
2453
2454     myAccumFrames = 0; // accumulation should be restarted
2455   }
2456
2457   return Standard_True;
2458 }
2459
2460 // =======================================================================
2461 // function : setUniformState
2462 // purpose  : Sets uniform state for the given ray-tracing shader program
2463 // =======================================================================
2464 Standard_Boolean OpenGl_View::setUniformState (const Standard_Integer        theProgramId,
2465                                                const Standard_Integer        theWinSizeX,
2466                                                const Standard_Integer        theWinSizeY,
2467                                                Graphic3d_Camera::Projection  theProjection,
2468                                                const Handle(OpenGl_Context)& theGlContext)
2469 {
2470   // Get projection state
2471   OpenGl_MatrixState<Standard_ShortReal>& aCntxProjectionState = theGlContext->ProjectionState;
2472
2473   OpenGl_Mat4 aViewPrjMat;
2474   OpenGl_Mat4 anUnviewMat;
2475   OpenGl_Vec3 aOrigins[4];
2476   OpenGl_Vec3 aDirects[4];
2477
2478   if (myCamera->IsOrthographic()
2479    || !myRenderParams.IsGlobalIlluminationEnabled)
2480   {
2481     updateCamera (myCamera->OrientationMatrixF(),
2482                   aCntxProjectionState.Current(),
2483                   aOrigins,
2484                   aDirects,
2485                   aViewPrjMat,
2486                   anUnviewMat);
2487   }
2488   else
2489   {
2490     updatePerspCameraPT (myCamera->OrientationMatrixF(),
2491                          aCntxProjectionState.Current(),
2492                          theProjection,
2493                          aViewPrjMat,
2494                          anUnviewMat,
2495                          theWinSizeX,
2496                          theWinSizeY);
2497   }
2498
2499   Handle(OpenGl_ShaderProgram)& theProgram = theProgramId == 0
2500                                            ? myRaytraceProgram
2501                                            : myPostFSAAProgram;
2502
2503   if (theProgram.IsNull())
2504   {
2505     return Standard_False;
2506   }
2507   
2508   theProgram->SetUniform(theGlContext, "uEyeOrig", myEyeOrig);
2509   theProgram->SetUniform(theGlContext, "uEyeView", myEyeView);
2510   theProgram->SetUniform(theGlContext, "uEyeVert", myEyeVert);
2511   theProgram->SetUniform(theGlContext, "uEyeSide", myEyeSide);
2512   theProgram->SetUniform(theGlContext, "uEyeSize", myEyeSize);
2513
2514   theProgram->SetUniform(theGlContext, "uApertureRadius", myRenderParams.CameraApertureRadius);
2515   theProgram->SetUniform(theGlContext, "uFocalPlaneDist", myRenderParams.CameraFocalPlaneDist);
2516   
2517   // Set camera state
2518   theProgram->SetUniform (theGlContext,
2519     myUniformLocations[theProgramId][OpenGl_RT_uOriginLB], aOrigins[0]);
2520   theProgram->SetUniform (theGlContext,
2521     myUniformLocations[theProgramId][OpenGl_RT_uOriginRB], aOrigins[1]);
2522   theProgram->SetUniform (theGlContext,
2523     myUniformLocations[theProgramId][OpenGl_RT_uOriginLT], aOrigins[2]);
2524   theProgram->SetUniform (theGlContext,
2525     myUniformLocations[theProgramId][OpenGl_RT_uOriginRT], aOrigins[3]);
2526   theProgram->SetUniform (theGlContext,
2527     myUniformLocations[theProgramId][OpenGl_RT_uDirectLB], aDirects[0]);
2528   theProgram->SetUniform (theGlContext,
2529     myUniformLocations[theProgramId][OpenGl_RT_uDirectRB], aDirects[1]);
2530   theProgram->SetUniform (theGlContext,
2531     myUniformLocations[theProgramId][OpenGl_RT_uDirectLT], aDirects[2]);
2532   theProgram->SetUniform (theGlContext,
2533     myUniformLocations[theProgramId][OpenGl_RT_uDirectRT], aDirects[3]);
2534   theProgram->SetUniform (theGlContext,
2535     myUniformLocations[theProgramId][OpenGl_RT_uViewPrMat], aViewPrjMat);
2536   theProgram->SetUniform (theGlContext,
2537     myUniformLocations[theProgramId][OpenGl_RT_uUnviewMat], anUnviewMat);
2538
2539   // Set screen dimensions
2540   myRaytraceProgram->SetUniform (theGlContext,
2541     myUniformLocations[theProgramId][OpenGl_RT_uWinSizeX], theWinSizeX);
2542   myRaytraceProgram->SetUniform (theGlContext,
2543     myUniformLocations[theProgramId][OpenGl_RT_uWinSizeY], theWinSizeY);
2544
2545   // Set 3D scene parameters
2546   theProgram->SetUniform (theGlContext,
2547     myUniformLocations[theProgramId][OpenGl_RT_uSceneRad], myRaytraceSceneRadius);
2548   theProgram->SetUniform (theGlContext,
2549     myUniformLocations[theProgramId][OpenGl_RT_uSceneEps], myRaytraceSceneEpsilon);
2550
2551   // Set light source parameters
2552   const Standard_Integer aLightSourceBufferSize =
2553     static_cast<Standard_Integer> (myRaytraceGeometry.Sources.size());
2554   
2555   theProgram->SetUniform (theGlContext,
2556     myUniformLocations[theProgramId][OpenGl_RT_uLightCount], aLightSourceBufferSize);
2557
2558   // Set array of 64-bit texture handles
2559   if (theGlContext->arbTexBindless != NULL && myRaytraceGeometry.HasTextures())
2560   {
2561     const std::vector<GLuint64>& aTextures = myRaytraceGeometry.TextureHandles();
2562
2563     theProgram->SetUniform (theGlContext, myUniformLocations[theProgramId][OpenGl_RT_uTexSamplersArray],
2564       static_cast<GLsizei> (aTextures.size()), reinterpret_cast<const OpenGl_Vec2u*> (&aTextures.front()));
2565   }
2566
2567   // Set background colors (only gradient background supported)
2568   if (myBackgrounds[Graphic3d_TOB_GRADIENT] != NULL
2569    && myBackgrounds[Graphic3d_TOB_GRADIENT]->IsDefined())
2570   {
2571     theProgram->SetUniform (theGlContext,
2572       myUniformLocations[theProgramId][OpenGl_RT_uBackColorTop], myBackgrounds[Graphic3d_TOB_GRADIENT]->GradientColor (0));
2573     theProgram->SetUniform (theGlContext,
2574       myUniformLocations[theProgramId][OpenGl_RT_uBackColorBot], myBackgrounds[Graphic3d_TOB_GRADIENT]->GradientColor (1));
2575   }
2576   else
2577   {
2578     const OpenGl_Vec4& aBackColor = myBgColor;
2579
2580     theProgram->SetUniform (theGlContext,
2581       myUniformLocations[theProgramId][OpenGl_RT_uBackColorTop], aBackColor);
2582     theProgram->SetUniform (theGlContext,
2583       myUniformLocations[theProgramId][OpenGl_RT_uBackColorBot], aBackColor);
2584   }
2585
2586   // Set environment map parameters
2587   const Standard_Boolean toDisableEnvironmentMap = myTextureEnv.IsNull()
2588                                                ||  myTextureEnv->IsEmpty()
2589                                                || !myTextureEnv->First()->IsValid();
2590
2591   theProgram->SetUniform (theGlContext,
2592     myUniformLocations[theProgramId][OpenGl_RT_uSphereMapEnabled], toDisableEnvironmentMap ? 0 : 1);
2593
2594   theProgram->SetUniform (theGlContext,
2595     myUniformLocations[theProgramId][OpenGl_RT_uSphereMapForBack], myRenderParams.UseEnvironmentMapBackground ?  1 : 0);
2596
2597   if (myRenderParams.IsGlobalIlluminationEnabled) // GI parameters
2598   {
2599     theProgram->SetUniform (theGlContext,
2600       myUniformLocations[theProgramId][OpenGl_RT_uMaxRadiance], myRenderParams.RadianceClampingValue);
2601
2602     theProgram->SetUniform (theGlContext,
2603       myUniformLocations[theProgramId][OpenGl_RT_uBlockedRngEnabled], myRenderParams.CoherentPathTracingMode ? 1 : 0);
2604
2605     // Check whether we should restart accumulation for run-time parameters
2606     if (myRenderParams.RadianceClampingValue       != myRaytraceParameters.RadianceClampingValue
2607      || myRenderParams.UseEnvironmentMapBackground != myRaytraceParameters.UseEnvMapForBackground)
2608     {
2609       myAccumFrames = 0; // accumulation should be restarted
2610
2611       myRaytraceParameters.RadianceClampingValue  = myRenderParams.RadianceClampingValue;
2612       myRaytraceParameters.UseEnvMapForBackground = myRenderParams.UseEnvironmentMapBackground;
2613     }
2614   }
2615   else // RT parameters
2616   {
2617     // Set ambient light source
2618     theProgram->SetUniform (theGlContext,
2619       myUniformLocations[theProgramId][OpenGl_RT_uLightAmbnt], myRaytraceGeometry.Ambient);
2620
2621     // Enable/disable run-time ray-tracing effects
2622     theProgram->SetUniform (theGlContext,
2623       myUniformLocations[theProgramId][OpenGl_RT_uShadowsEnabled], myRenderParams.IsShadowEnabled ?  1 : 0);
2624     theProgram->SetUniform (theGlContext,
2625       myUniformLocations[theProgramId][OpenGl_RT_uReflectEnabled], myRenderParams.IsReflectionEnabled ?  1 : 0);
2626   }
2627
2628   return Standard_True;
2629 }
2630
2631 // =======================================================================
2632 // function : bindRaytraceTextures
2633 // purpose  : Binds ray-trace textures to corresponding texture units
2634 // =======================================================================
2635 void OpenGl_View::bindRaytraceTextures (const Handle(OpenGl_Context)& theGlContext,
2636                                         int theStereoView)
2637 {
2638   if (myRaytraceParameters.AdaptiveScreenSampling
2639    && myRaytraceParameters.GlobalIllumination)
2640   {
2641   #if !defined(GL_ES_VERSION_2_0)
2642     theGlContext->core42->glBindImageTexture (OpenGl_RT_OutputImage,
2643                                               myRaytraceOutputTexture[theStereoView]->TextureId(), 0, GL_TRUE, 0, GL_READ_WRITE, GL_R32F);
2644     theGlContext->core42->glBindImageTexture (OpenGl_RT_VisualErrorImage,
2645                                               myRaytraceVisualErrorTexture[theStereoView]->TextureId(), 0, GL_TRUE, 0, GL_READ_WRITE, GL_R32I);
2646     if (myRaytraceParameters.AdaptiveScreenSamplingAtomic)
2647     {
2648       theGlContext->core42->glBindImageTexture (OpenGl_RT_TileOffsetsImage,
2649                                                 myRaytraceTileOffsetsTexture[theStereoView]->TextureId(), 0, GL_TRUE, 0, GL_READ_ONLY, GL_RG32I);
2650     }
2651     else
2652     {
2653       theGlContext->core42->glBindImageTexture (OpenGl_RT_TileSamplesImage,
2654                                                 myRaytraceTileSamplesTexture[theStereoView]->TextureId(), 0, GL_TRUE, 0, GL_READ_WRITE, GL_R32I);
2655     }
2656   #else
2657     (void )theStereoView;
2658   #endif
2659   }
2660
2661   if (!myTextureEnv.IsNull()
2662    && !myTextureEnv->IsEmpty()
2663    &&  myTextureEnv->First()->IsValid())
2664   {
2665     myTextureEnv->First()->Bind (theGlContext, OpenGl_RT_EnvironmentMapTexture);
2666   }
2667
2668   mySceneMinPointTexture   ->BindTexture (theGlContext, OpenGl_RT_SceneMinPointTexture);
2669   mySceneMaxPointTexture   ->BindTexture (theGlContext, OpenGl_RT_SceneMaxPointTexture);
2670   mySceneNodeInfoTexture   ->BindTexture (theGlContext, OpenGl_RT_SceneNodeInfoTexture);
2671   myGeometryVertexTexture  ->BindTexture (theGlContext, OpenGl_RT_GeometryVertexTexture);
2672   myGeometryNormalTexture  ->BindTexture (theGlContext, OpenGl_RT_GeometryNormalTexture);
2673   myGeometryTexCrdTexture  ->BindTexture (theGlContext, OpenGl_RT_GeometryTexCrdTexture);
2674   myGeometryTriangTexture  ->BindTexture (theGlContext, OpenGl_RT_GeometryTriangTexture);
2675   mySceneTransformTexture  ->BindTexture (theGlContext, OpenGl_RT_SceneTransformTexture);
2676   myRaytraceMaterialTexture->BindTexture (theGlContext, OpenGl_RT_RaytraceMaterialTexture);
2677   myRaytraceLightSrcTexture->BindTexture (theGlContext, OpenGl_RT_RaytraceLightSrcTexture);
2678 }
2679
2680 // =======================================================================
2681 // function : unbindRaytraceTextures
2682 // purpose  : Unbinds ray-trace textures from corresponding texture units
2683 // =======================================================================
2684 void OpenGl_View::unbindRaytraceTextures (const Handle(OpenGl_Context)& theGlContext)
2685 {
2686   mySceneMinPointTexture   ->UnbindTexture (theGlContext, OpenGl_RT_SceneMinPointTexture);
2687   mySceneMaxPointTexture   ->UnbindTexture (theGlContext, OpenGl_RT_SceneMaxPointTexture);
2688   mySceneNodeInfoTexture   ->UnbindTexture (theGlContext, OpenGl_RT_SceneNodeInfoTexture);
2689   myGeometryVertexTexture  ->UnbindTexture (theGlContext, OpenGl_RT_GeometryVertexTexture);
2690   myGeometryNormalTexture  ->UnbindTexture (theGlContext, OpenGl_RT_GeometryNormalTexture);
2691   myGeometryTexCrdTexture  ->UnbindTexture (theGlContext, OpenGl_RT_GeometryTexCrdTexture);
2692   myGeometryTriangTexture  ->UnbindTexture (theGlContext, OpenGl_RT_GeometryTriangTexture);
2693   mySceneTransformTexture  ->UnbindTexture (theGlContext, OpenGl_RT_SceneTransformTexture);
2694   myRaytraceMaterialTexture->UnbindTexture (theGlContext, OpenGl_RT_RaytraceMaterialTexture);
2695   myRaytraceLightSrcTexture->UnbindTexture (theGlContext, OpenGl_RT_RaytraceLightSrcTexture);
2696
2697   theGlContext->core15fwd->glActiveTexture (GL_TEXTURE0);
2698 }
2699
2700 // =======================================================================
2701 // function : runRaytraceShaders
2702 // purpose  : Runs ray-tracing shader programs
2703 // =======================================================================
2704 Standard_Boolean OpenGl_View::runRaytraceShaders (const Standard_Integer        theSizeX,
2705                                                   const Standard_Integer        theSizeY,
2706                                                   Graphic3d_Camera::Projection  theProjection,
2707                                                   OpenGl_FrameBuffer*           theReadDrawFbo,
2708                                                   const Handle(OpenGl_Context)& theGlContext)
2709 {
2710   Standard_Boolean aResult = theGlContext->BindProgram (myRaytraceProgram);
2711
2712   aResult &= setUniformState (0,
2713                               theSizeX,
2714                               theSizeY,
2715                               theProjection,
2716                               theGlContext);
2717
2718   if (myRaytraceParameters.GlobalIllumination) // path tracing
2719   {
2720     aResult &= runPathtrace    (theSizeX, theSizeY, theProjection, theGlContext);
2721     aResult &= runPathtraceOut (theProjection, theReadDrawFbo, theGlContext);
2722   }
2723   else // Whitted-style ray-tracing
2724   {
2725     aResult &= runRaytrace (theSizeX, theSizeY, theProjection, theReadDrawFbo, theGlContext);
2726   }
2727
2728   return aResult;
2729 }
2730
2731 // =======================================================================
2732 // function : runRaytrace
2733 // purpose  : Runs Whitted-style ray-tracing
2734 // =======================================================================
2735 Standard_Boolean OpenGl_View::runRaytrace (const Standard_Integer        theSizeX,
2736                                            const Standard_Integer        theSizeY,
2737                                            Graphic3d_Camera::Projection  theProjection,
2738                                            OpenGl_FrameBuffer*           theReadDrawFbo,
2739                                            const Handle(OpenGl_Context)& theGlContext)
2740 {
2741   Standard_Boolean aResult = Standard_True;
2742
2743   // Choose proper set of frame buffers for stereo rendering
2744   const Standard_Integer aFBOIdx = (theProjection == Graphic3d_Camera::Projection_MonoRightEye) ? 1 : 0;
2745   bindRaytraceTextures (theGlContext, aFBOIdx);
2746
2747   if (myRenderParams.IsAntialiasingEnabled) // if second FSAA pass is used
2748   {
2749     myRaytraceFBO1[aFBOIdx]->BindBuffer (theGlContext);
2750
2751     glClear (GL_DEPTH_BUFFER_BIT); // render the image with depth
2752   }
2753
2754   theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
2755
2756   if (myRenderParams.IsAntialiasingEnabled)
2757   {
2758     glDisable (GL_DEPTH_TEST); // improve jagged edges without depth buffer
2759
2760     // bind ray-tracing output image as input
2761     myRaytraceFBO1[aFBOIdx]->ColorTexture()->Bind (theGlContext, OpenGl_RT_FsaaInputTexture);
2762
2763     aResult &= theGlContext->BindProgram (myPostFSAAProgram);
2764
2765     aResult &= setUniformState (1 /* FSAA ID */,
2766                                 theSizeX,
2767                                 theSizeY,
2768                                 theProjection,
2769                                 theGlContext);
2770
2771     // Perform multi-pass adaptive FSAA using ping-pong technique.
2772     // We use 'FLIPTRI' sampling pattern changing for every pixel
2773     // (3 additional samples per pixel, the 1st sample is already
2774     // available from initial ray-traced image).
2775     for (Standard_Integer anIt = 1; anIt < 4; ++anIt)
2776     {
2777       GLfloat aOffsetX = 1.f / theSizeX;
2778       GLfloat aOffsetY = 1.f / theSizeY;
2779
2780       if (anIt == 1)
2781       {
2782         aOffsetX *= -0.55f;
2783         aOffsetY *=  0.55f;
2784       }
2785       else if (anIt == 2)
2786       {
2787         aOffsetX *=  0.00f;
2788         aOffsetY *= -0.55f;
2789       }
2790       else if (anIt == 3)
2791       {
2792         aOffsetX *= 0.55f;
2793         aOffsetY *= 0.00f;
2794       }
2795
2796       aResult &= myPostFSAAProgram->SetUniform (theGlContext,
2797         myUniformLocations[1][OpenGl_RT_uSamples], anIt + 1);
2798       aResult &= myPostFSAAProgram->SetUniform (theGlContext,
2799         myUniformLocations[1][OpenGl_RT_uOffsetX], aOffsetX);
2800       aResult &= myPostFSAAProgram->SetUniform (theGlContext,
2801         myUniformLocations[1][OpenGl_RT_uOffsetY], aOffsetY);
2802
2803       Handle(OpenGl_FrameBuffer)& aFramebuffer = anIt % 2
2804                                                ? myRaytraceFBO2[aFBOIdx]
2805                                                : myRaytraceFBO1[aFBOIdx];
2806
2807       aFramebuffer->BindBuffer (theGlContext);
2808
2809       // perform adaptive FSAA pass
2810       theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
2811
2812       aFramebuffer->ColorTexture()->Bind (theGlContext, OpenGl_RT_FsaaInputTexture);
2813     }
2814
2815     const Handle(OpenGl_FrameBuffer)& aRenderImageFramebuffer = myRaytraceFBO2[aFBOIdx];
2816     const Handle(OpenGl_FrameBuffer)& aDepthSourceFramebuffer = myRaytraceFBO1[aFBOIdx];
2817
2818     glEnable (GL_DEPTH_TEST);
2819
2820     // Display filtered image
2821     theGlContext->BindProgram (myOutImageProgram);
2822
2823     if (theReadDrawFbo != NULL)
2824     {
2825       theReadDrawFbo->BindBuffer (theGlContext);
2826     }
2827     else
2828     {
2829       aRenderImageFramebuffer->UnbindBuffer (theGlContext);
2830     }
2831
2832     aRenderImageFramebuffer->ColorTexture()       ->Bind (theGlContext, OpenGl_RT_PrevAccumTexture);
2833     aDepthSourceFramebuffer->DepthStencilTexture()->Bind (theGlContext, OpenGl_RT_RaytraceDepthTexture);
2834
2835     // copy the output image with depth values
2836     theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
2837
2838     aDepthSourceFramebuffer->DepthStencilTexture()->Unbind (theGlContext, OpenGl_RT_RaytraceDepthTexture);
2839     aRenderImageFramebuffer->ColorTexture()       ->Unbind (theGlContext, OpenGl_RT_PrevAccumTexture);
2840   }
2841
2842   unbindRaytraceTextures (theGlContext);
2843
2844   theGlContext->BindProgram (NULL);
2845
2846   return aResult;
2847 }
2848
2849 // =======================================================================
2850 // function : runPathtrace
2851 // purpose  : Runs path tracing shader
2852 // =======================================================================
2853 Standard_Boolean OpenGl_View::runPathtrace (const Standard_Integer              theSizeX,
2854                                             const Standard_Integer              theSizeY,
2855                                             const Graphic3d_Camera::Projection  theProjection,
2856                                             const Handle(OpenGl_Context)&       theGlContext)
2857 {
2858   if (myToUpdateEnvironmentMap) // check whether the map was changed
2859   {
2860     myAccumFrames = myToUpdateEnvironmentMap = 0;
2861   }
2862   
2863   if (myRenderParams.CameraApertureRadius != myPrevCameraApertureRadius
2864    || myRenderParams.CameraFocalPlaneDist != myPrevCameraFocalPlaneDist)
2865   {
2866     myPrevCameraApertureRadius = myRenderParams.CameraApertureRadius;
2867     myPrevCameraFocalPlaneDist = myRenderParams.CameraFocalPlaneDist;
2868     myAccumFrames = 0;
2869   }
2870
2871   // Choose proper set of frame buffers for stereo rendering
2872   const Standard_Integer aFBOIdx = (theProjection == Graphic3d_Camera::Projection_MonoRightEye) ? 1 : 0;
2873
2874   if (myRaytraceParameters.AdaptiveScreenSampling)
2875   {
2876     if (myAccumFrames == 0)
2877     {
2878       myTileSampler.Reset(); // reset tile sampler to its initial state
2879
2880       // Adaptive sampling is starting at the second frame
2881       if (myRaytraceParameters.AdaptiveScreenSamplingAtomic)
2882       {
2883         myTileSampler.UploadOffsets (theGlContext, myRaytraceTileOffsetsTexture[aFBOIdx], false);
2884       }
2885       else
2886       {
2887         myTileSampler.UploadSamples (theGlContext, myRaytraceTileSamplesTexture[aFBOIdx], false);
2888       }
2889
2890     #if !defined(GL_ES_VERSION_2_0)
2891       theGlContext->core44->glClearTexImage (myRaytraceOutputTexture[aFBOIdx]->TextureId(), 0, GL_RED, GL_FLOAT, NULL);
2892     #endif
2893     }
2894
2895     // Clear adaptive screen sampling images
2896   #if !defined(GL_ES_VERSION_2_0)
2897     theGlContext->core44->glClearTexImage (myRaytraceVisualErrorTexture[aFBOIdx]->TextureId(), 0, GL_RED_INTEGER, GL_INT, NULL);
2898   #endif
2899   }
2900
2901   bindRaytraceTextures (theGlContext, aFBOIdx);
2902
2903   const Handle(OpenGl_FrameBuffer)& anAccumImageFramebuffer = myAccumFrames % 2 ? myRaytraceFBO2[aFBOIdx] : myRaytraceFBO1[aFBOIdx];
2904   anAccumImageFramebuffer->ColorTexture()->Bind (theGlContext, OpenGl_RT_PrevAccumTexture);
2905
2906   // Set frame accumulation weight
2907   myRaytraceProgram->SetUniform (theGlContext, myUniformLocations[0][OpenGl_RT_uAccumSamples], myAccumFrames);
2908
2909   // Set image uniforms for render program
2910   if (myRaytraceParameters.AdaptiveScreenSampling)
2911   {
2912     myRaytraceProgram->SetUniform (theGlContext, myUniformLocations[0][OpenGl_RT_uRenderImage], OpenGl_RT_OutputImage);
2913     myRaytraceProgram->SetUniform (theGlContext, myUniformLocations[0][OpenGl_RT_uTilesImage],  OpenGl_RT_TileSamplesImage);
2914     myRaytraceProgram->SetUniform (theGlContext, myUniformLocations[0][OpenGl_RT_uOffsetImage], OpenGl_RT_TileOffsetsImage);
2915     myRaytraceProgram->SetUniform (theGlContext, myUniformLocations[0][OpenGl_RT_uTileSize], myTileSampler.TileSize());
2916   }
2917
2918   const Handle(OpenGl_FrameBuffer)& aRenderImageFramebuffer = myAccumFrames % 2 ? myRaytraceFBO1[aFBOIdx] : myRaytraceFBO2[aFBOIdx];
2919   aRenderImageFramebuffer->BindBuffer (theGlContext);
2920   if (myRaytraceParameters.AdaptiveScreenSampling
2921    && myRaytraceParameters.AdaptiveScreenSamplingAtomic)
2922   {
2923     // extend viewport here, so that tiles at boundaries (cut tile size by target rendering viewport)
2924     // redirected to inner tiles (full tile size) are drawn entirely
2925     const Graphic3d_Vec2i anOffsetViewport = myTileSampler.OffsetTilesViewport (myAccumFrames > 1); // shrunk offsets texture will be uploaded since 3rd frame
2926     glViewport (0, 0, anOffsetViewport.x(), anOffsetViewport.y());
2927   }
2928
2929   // Generate for the given RNG seed
2930   glDisable (GL_DEPTH_TEST);
2931
2932   // Adaptive Screen Sampling computes the same overall amount of samples per frame redraw as normal Path Tracing,
2933   // but distributes them unequally across pixels (grouped in tiles), so that some pixels do not receive new samples at all.
2934   //
2935   // Offsets map (redirecting currently rendered tile to another tile) allows performing Adaptive Screen Sampling in single pass,
2936   // but current implementation relies on atomic float operations (AdaptiveScreenSamplingAtomic) for this.
2937   // So that when atomic floats are not supported by GPU, multi-pass rendering is used instead.
2938   //
2939   // Single-pass rendering is more optimal due to smaller amount of draw calls,
2940   // memory synchronization barriers, discarding most of the fragments and bad parallelization in case of very small amount of tiles requiring more samples.
2941   // However, atomic operations on float values still produces different result (close, but not bit exact) making non-regression testing not robust.
2942   // It should be possible following single-pass rendering approach but using extra accumulation buffer and resolving pass as possible improvement.
2943   const int aNbPasses = myRaytraceParameters.AdaptiveScreenSampling
2944                     && !myRaytraceParameters.AdaptiveScreenSamplingAtomic
2945                       ? myTileSampler.MaxTileSamples()
2946                       : 1;
2947   if (myAccumFrames == 0)
2948   {
2949     myRNG.SetSeed(); // start RNG from beginning
2950   }
2951   for (int aPassIter = 0; aPassIter < aNbPasses; ++aPassIter)
2952   {
2953     myRaytraceProgram->SetUniform (theGlContext, myUniformLocations[0][OpenGl_RT_uFrameRndSeed], static_cast<Standard_Integer> (myRNG.NextInt() >> 2));
2954     theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
2955     if (myRaytraceParameters.AdaptiveScreenSampling)
2956     {
2957     #if !defined(GL_ES_VERSION_2_0)
2958       theGlContext->core44->glMemoryBarrier (GL_SHADER_IMAGE_ACCESS_BARRIER_BIT);
2959     #endif
2960     }
2961   }
2962   aRenderImageFramebuffer->UnbindBuffer (theGlContext);
2963
2964   if (myRaytraceParameters.AdaptiveScreenSampling
2965    && myRaytraceParameters.AdaptiveScreenSamplingAtomic)
2966   {
2967     glViewport (0, 0, theSizeX, theSizeY);
2968   }
2969   return true;
2970 }
2971
2972 // =======================================================================
2973 // function : runPathtraceOut
2974 // purpose  :
2975 // =======================================================================
2976 Standard_Boolean OpenGl_View::runPathtraceOut (const Graphic3d_Camera::Projection  theProjection,
2977                                                OpenGl_FrameBuffer*                 theReadDrawFbo,
2978                                                const Handle(OpenGl_Context)&       theGlContext)
2979 {
2980   // Output accumulated path traced image
2981   theGlContext->BindProgram (myOutImageProgram);
2982
2983   // Choose proper set of frame buffers for stereo rendering
2984   const Standard_Integer aFBOIdx = (theProjection == Graphic3d_Camera::Projection_MonoRightEye) ? 1 : 0;
2985
2986   if (myRaytraceParameters.AdaptiveScreenSampling)
2987   {
2988     // Set uniforms for display program
2989     myOutImageProgram->SetUniform (theGlContext, "uRenderImage",   OpenGl_RT_OutputImage);
2990     myOutImageProgram->SetUniform (theGlContext, "uAccumFrames",   myAccumFrames);
2991     myOutImageProgram->SetUniform (theGlContext, "uVarianceImage", OpenGl_RT_VisualErrorImage);
2992     myOutImageProgram->SetUniform (theGlContext, "uDebugAdaptive", myRenderParams.ShowSamplingTiles ?  1 : 0);
2993     myOutImageProgram->SetUniform (theGlContext, "uTileSize",      myTileSampler.TileSize());
2994     myOutImageProgram->SetUniform (theGlContext, "uVarianceScaleFactor", myTileSampler.VarianceScaleFactor());
2995   }
2996
2997   if (myRaytraceParameters.GlobalIllumination)
2998   {
2999     myOutImageProgram->SetUniform(theGlContext, "uExposure", myRenderParams.Exposure);
3000     switch (myRaytraceParameters.ToneMappingMethod)
3001     {
3002       case Graphic3d_ToneMappingMethod_Disabled:
3003         break;
3004       case Graphic3d_ToneMappingMethod_Filmic:
3005         myOutImageProgram->SetUniform (theGlContext, "uWhitePoint", myRenderParams.WhitePoint);
3006         break;
3007     }
3008   }
3009
3010   if (theReadDrawFbo != NULL)
3011   {
3012     theReadDrawFbo->BindBuffer (theGlContext);
3013   }
3014
3015   const Handle(OpenGl_FrameBuffer)& aRenderImageFramebuffer = myAccumFrames % 2 ? myRaytraceFBO1[aFBOIdx] : myRaytraceFBO2[aFBOIdx];
3016   aRenderImageFramebuffer->ColorTexture()->Bind (theGlContext, OpenGl_RT_PrevAccumTexture);
3017
3018   // Copy accumulated image with correct depth values
3019   glEnable (GL_DEPTH_TEST);
3020   theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
3021
3022   aRenderImageFramebuffer->ColorTexture()->Unbind (theGlContext, OpenGl_RT_PrevAccumTexture);
3023
3024   if (myRaytraceParameters.AdaptiveScreenSampling)
3025   {
3026     // Download visual error map from the GPU and build adjusted tile offsets for optimal image sampling
3027     myTileSampler.GrabVarianceMap (theGlContext, myRaytraceVisualErrorTexture[aFBOIdx]);
3028     if (myRaytraceParameters.AdaptiveScreenSamplingAtomic)
3029     {
3030       myTileSampler.UploadOffsets (theGlContext, myRaytraceTileOffsetsTexture[aFBOIdx], myAccumFrames != 0);
3031     }
3032     else
3033     {
3034       myTileSampler.UploadSamples (theGlContext, myRaytraceTileSamplesTexture[aFBOIdx], myAccumFrames != 0);
3035     }
3036   }
3037
3038   unbindRaytraceTextures (theGlContext);
3039   theGlContext->BindProgram (NULL);
3040   return true;
3041 }
3042
3043 // =======================================================================
3044 // function : raytrace
3045 // purpose  : Redraws the window using OpenGL/GLSL ray-tracing
3046 // =======================================================================
3047 Standard_Boolean OpenGl_View::raytrace (const Standard_Integer        theSizeX,
3048                                         const Standard_Integer        theSizeY,
3049                                         Graphic3d_Camera::Projection  theProjection,
3050                                         OpenGl_FrameBuffer*           theReadDrawFbo,
3051                                         const Handle(OpenGl_Context)& theGlContext)
3052 {
3053   if (!initRaytraceResources (theSizeX, theSizeY, theGlContext))
3054   {
3055     return Standard_False;
3056   }
3057
3058   if (!updateRaytraceBuffers (theSizeX, theSizeY, theGlContext))
3059   {
3060     return Standard_False;
3061   }
3062
3063   OpenGl_Mat4 aLightSourceMatrix;
3064
3065   // Get inversed model-view matrix for transforming lights
3066   myCamera->OrientationMatrixF().Inverted (aLightSourceMatrix);
3067
3068   if (!updateRaytraceLightSources (aLightSourceMatrix, theGlContext))
3069   {
3070     return Standard_False;
3071   }
3072
3073   // Generate image using Whitted-style ray-tracing or path tracing
3074   if (myIsRaytraceDataValid)
3075   {
3076     myRaytraceScreenQuad.BindVertexAttrib (theGlContext, Graphic3d_TOA_POS);
3077
3078     if (!myRaytraceGeometry.AcquireTextures (theGlContext))
3079     {
3080       theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR,
3081         0, GL_DEBUG_SEVERITY_MEDIUM, "Error: Failed to acquire OpenGL image textures");
3082     }
3083
3084     glDisable (GL_BLEND);
3085
3086     const Standard_Boolean aResult = runRaytraceShaders (theSizeX,
3087                                                          theSizeY,
3088                                                          theProjection,
3089                                                          theReadDrawFbo,
3090                                                          theGlContext);
3091
3092     if (!aResult)
3093     {
3094       theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR,
3095         0, GL_DEBUG_SEVERITY_MEDIUM, "Error: Failed to execute ray-tracing shaders");
3096     }
3097
3098     if (!myRaytraceGeometry.ReleaseTextures (theGlContext))
3099     {
3100       theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR,
3101         0, GL_DEBUG_SEVERITY_MEDIUM, "Error: Failed to release OpenGL image textures");
3102     }
3103
3104     myRaytraceScreenQuad.UnbindVertexAttrib (theGlContext, Graphic3d_TOA_POS);
3105   }
3106
3107   return Standard_True;
3108 }