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