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