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