9f4e4fb3e8631abd1f4ed35b7e8ecc002208fe56
[occt.git] / src / OpenGl / OpenGl_Workspace_Raytrace.cxx
1 // Created on: 2013-08-27
2 // Created by: Denis BOGOLEPOV
3 // Copyright (c) 2013 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_Workspace.hxx>
17
18 #include <Graphic3d_TextureParams.hxx>
19 #include <OpenGl_FrameBuffer.hxx>
20 #include <OpenGl_PrimitiveArray.hxx>
21 #include <OpenGl_VertexBuffer.hxx>
22 #include <OpenGl_View.hxx>
23 #include <OSD_File.hxx>
24 #include <OSD_Protection.hxx>
25
26 using namespace OpenGl_Raytrace;
27
28 //! Use this macro to output ray-tracing debug info
29 // #define RAY_TRACE_PRINT_INFO
30
31 #ifdef RAY_TRACE_PRINT_INFO
32   #include <OSD_Timer.hxx>
33 #endif
34
35 // =======================================================================
36 // function : UpdateRaytraceGeometry
37 // purpose  : Updates 3D scene geometry for ray tracing
38 // =======================================================================
39 Standard_Boolean OpenGl_Workspace::UpdateRaytraceGeometry (GeomUpdateMode theMode)
40 {
41   if (myView.IsNull())
42     return Standard_False;
43
44   // Note: In 'check' mode (OpenGl_GUM_CHECK) the scene geometry is analyzed for modifications
45   // This is light-weight procedure performed for each frame
46
47   if (theMode == OpenGl_GUM_CHECK)
48   {
49      if (myLayersModificationStatus != myView->LayerList().ModificationState())
50      {
51         return UpdateRaytraceGeometry (OpenGl_GUM_PREPARE);
52      }
53   } 
54   else if (theMode == OpenGl_GUM_PREPARE)
55   {
56     myRaytraceGeometry.ClearMaterials();
57     myArrayToTrianglesMap.clear();
58
59     myIsRaytraceDataValid = Standard_False;
60   }
61
62   // The set of processed structures (reflected to ray-tracing)
63   // This set is used to remove out-of-date records from the
64   // hash map of structures
65   std::set<const OpenGl_Structure*> anElements;
66
67   // Set of all currently visible and "raytracable" primitive arrays.
68   std::set<Standard_Size> anArrayIDs;
69
70   const OpenGl_LayerList& aList = myView->LayerList();
71
72   for (OpenGl_SequenceOfLayers::Iterator anLayerIt (aList.Layers()); anLayerIt.More(); anLayerIt.Next())
73   {
74     const OpenGl_PriorityList& aPriorityList = anLayerIt.Value().PriorityList();
75
76     if (aPriorityList.NbStructures() == 0)
77       continue;
78
79     const OpenGl_ArrayOfStructure& aStructArray = aPriorityList.ArrayOfStructures();
80
81     for (Standard_Integer anIndex = 0; anIndex < aStructArray.Length(); ++anIndex)
82     {
83       OpenGl_SequenceOfStructure::Iterator aStructIt;
84
85       for (aStructIt.Init (aStructArray (anIndex)); aStructIt.More(); aStructIt.Next())
86       {
87         const OpenGl_Structure* aStructure = aStructIt.Value();
88
89         if (theMode == OpenGl_GUM_CHECK)
90         {
91           if (CheckRaytraceStructure (aStructure))
92           {
93             return UpdateRaytraceGeometry (OpenGl_GUM_PREPARE);
94           }
95         }
96         else if (theMode == OpenGl_GUM_PREPARE)
97         {
98           if (!aStructure->IsRaytracable()
99            || !aStructure->IsVisible())
100             continue;
101
102           for (OpenGl_Structure::GroupIterator aGroupIter (aStructure->DrawGroups()); aGroupIter.More(); aGroupIter.Next())
103           {
104             // OpenGL elements from group (extract primitives arrays)
105             for (const OpenGl_ElementNode* aNode = aGroupIter.Value()->FirstNode(); aNode != NULL; aNode = aNode->next)
106             {
107               OpenGl_PrimitiveArray* aPrimArray = dynamic_cast<OpenGl_PrimitiveArray*> (aNode->elem);
108
109               if (aPrimArray != NULL)
110               {
111                 // Collect all primitive arrays in scene.
112                 anArrayIDs.insert (aPrimArray->GetUID());
113               }
114             }
115           }
116         }
117         else if (theMode == OpenGl_GUM_UPDATE)
118         {
119           if (!aStructure->IsRaytracable())
120             continue;
121
122           AddRaytraceStructure (aStructure, anElements);
123         }
124       }
125     }
126   }
127
128   if (theMode == OpenGl_GUM_PREPARE)
129   {
130     BVH_ObjectSet<Standard_ShortReal, 3>::BVH_ObjectList anUnchangedObjects;
131
132     // Leave only unchanged objects in myRaytraceGeometry so only their transforms and materials will be updated
133     // Objects which not in myArrayToTrianglesMap will be built from scratch.
134     for (Standard_Integer anObjectIdx = 0; anObjectIdx < myRaytraceGeometry.Objects().Size(); ++anObjectIdx)
135     {
136       OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
137         myRaytraceGeometry.Objects().ChangeValue (anObjectIdx).operator->());
138
139       // If primitive array of object not in "anArrays" set then it was hided or deleted.
140       // If primitive array present in "anArrays" set but we don't have associated object yet, then
141       // the object is new and still has to be built.
142       if ((aTriangleSet != NULL) && ((anArrayIDs.find (aTriangleSet->AssociatedPArrayID())) != anArrayIDs.end()))
143       {
144         anUnchangedObjects.Append (myRaytraceGeometry.Objects().Value (anObjectIdx));
145
146         myArrayToTrianglesMap[aTriangleSet->AssociatedPArrayID()] = aTriangleSet;
147       }
148     }
149
150     myRaytraceGeometry.Objects() = anUnchangedObjects;
151
152     return UpdateRaytraceGeometry (OpenGl_GUM_UPDATE);
153   }
154
155   if (theMode == OpenGl_GUM_UPDATE)
156   {
157     // Actualize the hash map of structures -- remove out-of-date records
158     std::map<const OpenGl_Structure*, Standard_Size>::iterator anIter = myStructureStates.begin();
159
160     while (anIter != myStructureStates.end())
161     {
162       if (anElements.find (anIter->first) == anElements.end())
163       {
164         myStructureStates.erase (anIter++);
165       }
166       else
167       {
168         ++anIter;
169       }
170     }
171
172     // Actualize OpenGL layer list state
173     myLayersModificationStatus = myView->LayerList().ModificationState();
174
175     // Rebuild bottom-level and high-level BVHs
176     myRaytraceGeometry.ProcessAcceleration();
177
178     const Standard_ShortReal aMinRadius = Max (fabs (myRaytraceGeometry.Box().CornerMin().x()), Max (
179       fabs (myRaytraceGeometry.Box().CornerMin().y()), fabs (myRaytraceGeometry.Box().CornerMin().z())));
180     const Standard_ShortReal aMaxRadius = Max (fabs (myRaytraceGeometry.Box().CornerMax().x()), Max (
181       fabs (myRaytraceGeometry.Box().CornerMax().y()), fabs (myRaytraceGeometry.Box().CornerMax().z())));
182
183     myRaytraceSceneRadius = 2.f /* scale factor */ * Max (aMinRadius, aMaxRadius);
184
185     const BVH_Vec3f aSize = myRaytraceGeometry.Box().Size();
186
187     myRaytraceSceneEpsilon = Max (1e-6f, 1e-4f * sqrtf (
188       aSize.x() * aSize.x() + aSize.y() * aSize.y() + aSize.z() * aSize.z()));
189
190     return UploadRaytraceData();
191   }
192
193   return Standard_True;
194 }
195
196 // =======================================================================
197 // function : CheckRaytraceStructure
198 // purpose  : Checks to see if the structure is modified
199 // =======================================================================
200 Standard_Boolean OpenGl_Workspace::CheckRaytraceStructure (const OpenGl_Structure* theStructure)
201 {
202   if (!theStructure->IsRaytracable())
203   {
204     // Checks to see if all ray-tracable elements were
205     // removed from the structure
206     if (theStructure->ModificationState() > 0)
207     {
208       theStructure->ResetModificationState();
209       return Standard_True;
210     }
211
212     return Standard_False;
213   }
214
215   std::map<const OpenGl_Structure*, Standard_Size>::iterator aStructState = myStructureStates.find (theStructure);
216
217   if (aStructState != myStructureStates.end())
218     return aStructState->second != theStructure->ModificationState();
219
220   return Standard_True;
221 }
222
223 // =======================================================================
224 // function : BuildTexTransform
225 // purpose  : Constructs texture transformation matrix
226 // =======================================================================
227 void BuildTexTransform (const Handle(Graphic3d_TextureParams)& theParams, BVH_Mat4f& theMatrix)
228 {
229   theMatrix.InitIdentity();
230
231   // Apply scaling
232   const Graphic3d_Vec2& aScale = theParams->Scale();
233
234   theMatrix.ChangeValue (0, 0) *= aScale.x();
235   theMatrix.ChangeValue (1, 0) *= aScale.x();
236   theMatrix.ChangeValue (2, 0) *= aScale.x();
237   theMatrix.ChangeValue (3, 0) *= aScale.x();
238
239   theMatrix.ChangeValue (0, 1) *= aScale.y();
240   theMatrix.ChangeValue (1, 1) *= aScale.y();
241   theMatrix.ChangeValue (2, 1) *= aScale.y();
242   theMatrix.ChangeValue (3, 1) *= aScale.y();
243
244   // Apply translation
245   const Graphic3d_Vec2 aTrans = -theParams->Translation();
246
247   theMatrix.ChangeValue (0, 3) = theMatrix.GetValue (0, 0) * aTrans.x() +
248                                  theMatrix.GetValue (0, 1) * aTrans.y();
249
250   theMatrix.ChangeValue (1, 3) = theMatrix.GetValue (1, 0) * aTrans.x() +
251                                  theMatrix.GetValue (1, 1) * aTrans.y();
252
253   theMatrix.ChangeValue (2, 3) = theMatrix.GetValue (2, 0) * aTrans.x() +
254                                  theMatrix.GetValue (2, 1) * aTrans.y();
255
256   // Apply rotation
257   const Standard_ShortReal aSin = std::sin (
258     -theParams->Rotation() * static_cast<Standard_ShortReal> (M_PI / 180.0));
259   const Standard_ShortReal aCos = std::cos (
260     -theParams->Rotation() * static_cast<Standard_ShortReal> (M_PI / 180.0));
261
262   BVH_Mat4f aRotationMat;
263   aRotationMat.SetValue (0, 0,  aCos);
264   aRotationMat.SetValue (1, 1,  aCos);
265   aRotationMat.SetValue (0, 1, -aSin);
266   aRotationMat.SetValue (1, 0,  aSin);
267
268   theMatrix = theMatrix * aRotationMat;
269 }
270
271 // =======================================================================
272 // function : CreateMaterial
273 // purpose  : Creates ray-tracing material properties
274 // =======================================================================
275 Standard_Boolean OpenGl_Workspace::CreateMaterial (const OpenGl_AspectFace* theAspect, OpenGl_RaytraceMaterial& theMaterial)
276 {
277   const OPENGL_SURF_PROP& aProperties = theAspect->IntFront();
278
279   const Standard_ShortReal* aSrcAmbient =
280     aProperties.isphysic ? aProperties.ambcol.rgb : aProperties.matcol.rgb;
281
282   theMaterial.Ambient = BVH_Vec4f (aSrcAmbient[0] * aProperties.amb,
283                                    aSrcAmbient[1] * aProperties.amb,
284                                    aSrcAmbient[2] * aProperties.amb,
285                                    1.f);
286
287   const Standard_ShortReal* aSrcDiffuse =
288     aProperties.isphysic ? aProperties.difcol.rgb : aProperties.matcol.rgb;
289
290   theMaterial.Diffuse = BVH_Vec4f (aSrcDiffuse[0] * aProperties.diff,
291                                    aSrcDiffuse[1] * aProperties.diff,
292                                    aSrcDiffuse[2] * aProperties.diff,
293                                    -1.f /* no texture */);
294
295   theMaterial.Specular = BVH_Vec4f (
296     (aProperties.isphysic ? aProperties.speccol.rgb[0] : 1.f) * aProperties.spec,
297     (aProperties.isphysic ? aProperties.speccol.rgb[1] : 1.f) * aProperties.spec,
298     (aProperties.isphysic ? aProperties.speccol.rgb[2] : 1.f) * aProperties.spec,
299     aProperties.shine);
300
301   const Standard_ShortReal* aSrcEmission =
302     aProperties.isphysic ? aProperties.emscol.rgb : aProperties.matcol.rgb;
303
304   theMaterial.Emission = BVH_Vec4f (aSrcEmission[0] * aProperties.emsv,
305                                     aSrcEmission[1] * aProperties.emsv,
306                                     aSrcEmission[2] * aProperties.emsv,
307                                     1.f);
308
309   // Note: Here we use sub-linear transparency function
310   // to produce realistic-looking transparency effect
311   theMaterial.Transparency = BVH_Vec4f (powf (aProperties.trans, 0.75f),
312                                         1.f - aProperties.trans,
313                                         aProperties.index == 0 ? 1.f : aProperties.index,
314                                         aProperties.index == 0 ? 1.f : 1.f / aProperties.index);
315
316   const Standard_ShortReal aMaxRefl = Max (theMaterial.Diffuse.x() + theMaterial.Specular.x(),
317                                       Max (theMaterial.Diffuse.y() + theMaterial.Specular.y(),
318                                            theMaterial.Diffuse.z() + theMaterial.Specular.z()));
319
320   const Standard_ShortReal aReflectionScale = 0.75f / aMaxRefl;
321
322   theMaterial.Reflection = BVH_Vec4f (
323     aProperties.speccol.rgb[0] * aProperties.spec * aReflectionScale,
324     aProperties.speccol.rgb[1] * aProperties.spec * aReflectionScale,
325     aProperties.speccol.rgb[2] * aProperties.spec * aReflectionScale,
326     0.f);
327
328   if (theAspect->DoTextureMap())
329   {
330     if (myGlContext->arbTexBindless != NULL)
331     {
332       BuildTexTransform (theAspect->TextureParams(), theMaterial.TextureTransform);
333       theMaterial.Diffuse.w() = static_cast<Standard_ShortReal> (
334         myRaytraceGeometry.AddTexture (theAspect->TextureRes (myGlContext)));
335     }
336     else if (!myIsRaytraceWarnTextures)
337     {
338       myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
339                                 GL_DEBUG_TYPE_PORTABILITY_ARB, 0, GL_DEBUG_SEVERITY_HIGH_ARB,
340                                 "Warning: texturing in Ray-Trace requires GL_ARB_bindless_texture extension which is missing. "
341                                 "Textures will be ignored.");
342       myIsRaytraceWarnTextures = Standard_True;
343     }
344   }
345
346   return Standard_True;
347 }
348
349 // =======================================================================
350 // function : AddRaytraceStructure
351 // purpose  : Adds OpenGL structure to ray-traced scene geometry
352 // =======================================================================
353 Standard_Boolean OpenGl_Workspace::AddRaytraceStructure (const OpenGl_Structure* theStructure, std::set<const OpenGl_Structure*>& theElements)
354 {
355   theElements.insert (theStructure);
356
357   if (!theStructure->IsVisible())
358   {
359     myStructureStates[theStructure] = theStructure->ModificationState();
360     return Standard_True;
361   }
362
363   // Get structure material
364   Standard_Integer aStructMatID = -1;
365
366   if (theStructure->AspectFace() != NULL)
367   {
368     aStructMatID = static_cast<Standard_Integer> (myRaytraceGeometry.Materials.size());
369
370     OpenGl_RaytraceMaterial aStructMaterial;
371     CreateMaterial (theStructure->AspectFace(), aStructMaterial);
372
373     myRaytraceGeometry.Materials.push_back (aStructMaterial);
374   }
375
376   Standard_ShortReal  aStructTransformArr[16];
377   Standard_ShortReal* aStructTransform = NULL;
378   if (theStructure->Transformation()->mat != NULL)
379   {
380     aStructTransform = aStructTransformArr;
381     for (Standard_Integer i = 0; i < 4; ++i)
382     {
383       for (Standard_Integer j = 0; j < 4; ++j)
384       {
385         aStructTransform[j * 4 + i] = theStructure->Transformation()->mat[i][j];
386       }
387     }
388   }
389
390   AddRaytraceGroups (theStructure, aStructMatID, aStructTransform);
391
392   // Process all connected OpenGL structures
393   for (OpenGl_ListOfStructure::Iterator anIts (theStructure->ConnectedStructures()); anIts.More(); anIts.Next())
394   {
395     if (anIts.Value()->IsRaytracable())
396       AddRaytraceGroups (anIts.Value(), aStructMatID, aStructTransform);
397   }
398
399   myStructureStates[theStructure] = theStructure->ModificationState();
400   return Standard_True;
401 }
402
403 // =======================================================================
404 // function : AddRaytraceGroups
405 // purpose  : Adds OpenGL groups to ray-traced scene geometry
406 // =======================================================================
407 Standard_Boolean OpenGl_Workspace::AddRaytraceGroups (const OpenGl_Structure*   theStructure,
408                                                       const Standard_Integer    theStructMatId,
409                                                       const Standard_ShortReal* theTransform)
410 {
411   for (OpenGl_Structure::GroupIterator aGroupIter (theStructure->DrawGroups()); aGroupIter.More(); aGroupIter.Next())
412   {
413     // Get group material
414     Standard_Integer aGroupMatID = -1;
415     if (aGroupIter.Value()->AspectFace() != NULL)
416     {
417       aGroupMatID = static_cast<Standard_Integer> (myRaytraceGeometry.Materials.size());
418
419       OpenGl_RaytraceMaterial aGroupMaterial;
420       CreateMaterial (aGroupIter.Value()->AspectFace(), aGroupMaterial);
421
422       myRaytraceGeometry.Materials.push_back (aGroupMaterial);
423     }
424
425     Standard_Integer aMatID = aGroupMatID < 0 ? theStructMatId : aGroupMatID;
426
427     if (aMatID < 0)
428     {
429       aMatID = static_cast<Standard_Integer> (myRaytraceGeometry.Materials.size());
430
431       myRaytraceGeometry.Materials.push_back (OpenGl_RaytraceMaterial());
432     }
433
434     // Add OpenGL elements from group (extract primitives arrays and aspects)
435     for (const OpenGl_ElementNode* aNode = aGroupIter.Value()->FirstNode(); aNode != NULL; aNode = aNode->next)
436     {
437       OpenGl_AspectFace* anAspect = dynamic_cast<OpenGl_AspectFace*> (aNode->elem);
438       if (anAspect != NULL)
439       {
440         aMatID = static_cast<Standard_Integer> (myRaytraceGeometry.Materials.size());
441
442         OpenGl_RaytraceMaterial aMaterial;
443         CreateMaterial (anAspect, aMaterial);
444
445         myRaytraceGeometry.Materials.push_back (aMaterial);
446       }
447       else
448       {
449         OpenGl_PrimitiveArray* aPrimArray = dynamic_cast<OpenGl_PrimitiveArray*> (aNode->elem);
450
451         if (aPrimArray != NULL)
452         {
453           std::map<Standard_Size, OpenGl_TriangleSet*>::iterator aSetIter = myArrayToTrianglesMap.find (aPrimArray->GetUID());
454
455           if (aSetIter != myArrayToTrianglesMap.end())
456           {
457             OpenGl_TriangleSet* aSet = aSetIter->second;
458
459             BVH_Transform<Standard_ShortReal, 4>* aTransform = new BVH_Transform<Standard_ShortReal, 4>();
460
461             if (theTransform != NULL)
462             {
463               aTransform->SetTransform (*(reinterpret_cast<const BVH_Mat4f*> (theTransform)));
464             }
465           
466             aSet->SetProperties (aTransform);
467
468             if (aSet->MaterialIndex() != OpenGl_TriangleSet::INVALID_MATERIAL && aSet->MaterialIndex() != aMatID)
469             {
470               aSet->SetMaterialIndex (aMatID);
471             }
472           }
473           else
474           {
475             NCollection_Handle<BVH_Object<Standard_ShortReal, 3> > aSet =
476               AddRaytracePrimitiveArray (aPrimArray, aMatID, 0);
477
478             if (!aSet.IsNull())
479             {
480               BVH_Transform<Standard_ShortReal, 4>* aTransform = new BVH_Transform<Standard_ShortReal, 4>;
481
482               if (theTransform != NULL)
483               {
484                 aTransform->SetTransform (*(reinterpret_cast<const BVH_Mat4f*> (theTransform)));
485               }
486
487               aSet->SetProperties (aTransform);
488
489               myRaytraceGeometry.Objects().Append (aSet);
490             }
491           }
492         }
493       }
494     }
495   }
496
497   return Standard_True;
498 }
499
500 // =======================================================================
501 // function : AddRaytracePrimitiveArray
502 // purpose  : Adds OpenGL primitive array to ray-traced scene geometry
503 // =======================================================================
504 OpenGl_TriangleSet* OpenGl_Workspace::AddRaytracePrimitiveArray (const OpenGl_PrimitiveArray* theArray,
505                                                                  Standard_Integer             theMatID,
506                                                                  const OpenGl_Mat4*           theTransform)
507 {
508   const Handle(Graphic3d_IndexBuffer)& anIndices = theArray->Indices();
509   const Handle(Graphic3d_Buffer)&      anAttribs = theArray->Attributes();
510   const Handle(Graphic3d_BoundBuffer)& aBounds   = theArray->Bounds();
511   if (theArray->DrawMode() < GL_TRIANGLES
512   #if !defined(GL_ES_VERSION_2_0)
513    || theArray->DrawMode() > GL_POLYGON
514   #else
515    || theArray->DrawMode() > GL_TRIANGLE_FAN
516   #endif
517    || anAttribs.IsNull())
518   {
519     return NULL;
520   }
521
522 #ifdef RAY_TRACE_PRINT_INFO
523   switch (theArray->DrawMode())
524   {
525     case GL_TRIANGLES:      std::cout << "\tAdding GL_TRIANGLES\n";      break;
526     case GL_TRIANGLE_FAN:   std::cout << "\tAdding GL_TRIANGLE_FAN\n";   break;
527     case GL_TRIANGLE_STRIP: std::cout << "\tAdding GL_TRIANGLE_STRIP\n"; break;
528   #if !defined(GL_ES_VERSION_2_0)
529     case GL_QUADS:          std::cout << "\tAdding GL_QUADS\n";          break;
530     case GL_QUAD_STRIP:     std::cout << "\tAdding GL_QUAD_STRIP\n";     break;
531     case GL_POLYGON:        std::cout << "\tAdding GL_POLYGON\n";        break;
532   #endif
533   }
534 #endif
535
536   OpenGl_Mat4 aNormalMatrix;
537
538   if (theTransform != NULL)
539   {
540     Standard_ASSERT_RETURN (theTransform->Inverted (aNormalMatrix),
541       "Error: Failed to compute normal transformation matrix", NULL);
542
543     aNormalMatrix.Transpose();
544   }
545
546   OpenGl_TriangleSet* aSet = new OpenGl_TriangleSet (theArray->GetUID());
547   {
548     aSet->Vertices.reserve (anAttribs->NbElements);
549     aSet->Normals .reserve (anAttribs->NbElements);
550     aSet->TexCrds .reserve (anAttribs->NbElements);
551
552     const size_t aVertFrom = aSet->Vertices.size();
553     for (Standard_Integer anAttribIter = 0; anAttribIter < anAttribs->NbAttributes; ++anAttribIter)
554     {
555       const Graphic3d_Attribute& anAttrib = anAttribs->Attribute       (anAttribIter);
556       const size_t               anOffset = anAttribs->AttributeOffset (anAttribIter);
557       if (anAttrib.Id == Graphic3d_TOA_POS)
558       {
559         if (anAttrib.DataType == Graphic3d_TOD_VEC3
560          || anAttrib.DataType == Graphic3d_TOD_VEC4)
561         {
562           for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
563           {
564             aSet->Vertices.push_back (
565               *reinterpret_cast<const Graphic3d_Vec3* >(anAttribs->value (aVertIter) + anOffset));
566           }
567         }
568         else if (anAttrib.DataType == Graphic3d_TOD_VEC2)
569         {
570           for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
571           {
572             const Graphic3d_Vec2& aVert = *reinterpret_cast<const Graphic3d_Vec2* >(anAttribs->value (aVertIter) + anOffset);
573             aSet->Vertices.push_back (BVH_Vec3f (aVert.x(), aVert.y(), 0.0f));
574           }
575         }
576       }
577       else if (anAttrib.Id == Graphic3d_TOA_NORM)
578       {
579         if (anAttrib.DataType == Graphic3d_TOD_VEC3
580          || anAttrib.DataType == Graphic3d_TOD_VEC4)
581         {
582           for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
583           {
584             aSet->Normals.push_back (
585               *reinterpret_cast<const Graphic3d_Vec3* >(anAttribs->value (aVertIter) + anOffset));
586           }
587         }
588       }
589       else if (anAttrib.Id == Graphic3d_TOA_UV)
590       {
591         if (anAttrib.DataType == Graphic3d_TOD_VEC2)
592         {
593           for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
594           {
595             aSet->TexCrds.push_back (
596               *reinterpret_cast<const Graphic3d_Vec2* >(anAttribs->value (aVertIter) + anOffset));
597           }
598         }
599       }
600     }
601
602     if (aSet->Normals.size() != aSet->Vertices.size())
603     {
604       for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
605       {
606         aSet->Normals.push_back (BVH_Vec3f());
607       }
608     }
609
610     if (aSet->TexCrds.size() != aSet->Vertices.size())
611     {
612       for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
613       {
614         aSet->TexCrds.push_back (BVH_Vec2f());
615       }
616     }
617
618     if (theTransform != NULL)
619     {
620       for (size_t aVertIter = aVertFrom; aVertIter < aSet->Vertices.size(); ++aVertIter)
621       {
622         BVH_Vec3f& aVertex = aSet->Vertices[aVertIter];
623
624         BVH_Vec4f aTransVertex =
625           *theTransform * BVH_Vec4f (aVertex.x(), aVertex.y(), aVertex.z(), 1.f);
626
627         aVertex = BVH_Vec3f (aTransVertex.x(), aTransVertex.y(), aTransVertex.z());
628       }
629       for (size_t aVertIter = aVertFrom; aVertIter < aSet->Normals.size(); ++aVertIter)
630       {
631         BVH_Vec3f& aNormal = aSet->Normals[aVertIter];
632
633         BVH_Vec4f aTransNormal =
634           aNormalMatrix * BVH_Vec4f (aNormal.x(), aNormal.y(), aNormal.z(), 0.f);
635
636         aNormal = BVH_Vec3f (aTransNormal.x(), aTransNormal.y(), aTransNormal.z());
637       }
638     }
639
640     if (!aBounds.IsNull())
641     {
642 #ifdef RAY_TRACE_PRINT_INFO
643       std::cout << "\tNumber of bounds = " << aBounds->NbBounds << std::endl;
644 #endif
645
646       Standard_Integer aBoundStart = 0;
647       for (Standard_Integer aBound = 0; aBound < aBounds->NbBounds; ++aBound)
648       {
649         const Standard_Integer aVertNum = aBounds->Bounds[aBound];
650
651 #ifdef RAY_TRACE_PRINT_INFO
652         std::cout << "\tAdding indices from bound " << aBound << ": " <<
653                                       aBoundStart << " .. " << aVertNum << std::endl;
654 #endif
655
656         if (!AddRaytraceVertexIndices (*aSet, *theArray, aBoundStart, aVertNum, theMatID))
657         {
658           delete aSet;
659           return NULL;
660         }
661
662         aBoundStart += aVertNum;
663       }
664     }
665     else
666     {
667       const Standard_Integer aVertNum = !anIndices.IsNull() ? anIndices->NbElements : anAttribs->NbElements;
668
669   #ifdef RAY_TRACE_PRINT_INFO
670         std::cout << "\tAdding indices from array: " << aVertNum << std::endl;
671   #endif
672
673       if (!AddRaytraceVertexIndices (*aSet, *theArray, 0, aVertNum, theMatID))
674       {
675         delete aSet;
676         return NULL;
677       }
678     }
679   }
680
681   if (aSet->Size() != 0)
682     aSet->MarkDirty();
683
684   return aSet;
685 }
686
687 // =======================================================================
688 // function : AddRaytraceVertexIndices
689 // purpose  : Adds vertex indices to ray-traced scene geometry
690 // =======================================================================
691 Standard_Boolean OpenGl_Workspace::AddRaytraceVertexIndices (OpenGl_TriangleSet&          theSet,
692                                                              const OpenGl_PrimitiveArray& theArray,
693                                                              Standard_Integer             theOffset,
694                                                              Standard_Integer             theCount,
695                                                              Standard_Integer             theMatID)
696 {
697   switch (theArray.DrawMode())
698   {
699     case GL_TRIANGLES:      return AddRaytraceTriangleArray        (theSet, theArray.Indices(), theOffset, theCount, theMatID);
700     case GL_TRIANGLE_FAN:   return AddRaytraceTriangleFanArray     (theSet, theArray.Indices(), theOffset, theCount, theMatID);
701     case GL_TRIANGLE_STRIP: return AddRaytraceTriangleStripArray   (theSet, theArray.Indices(), theOffset, theCount, theMatID);
702   #if !defined(GL_ES_VERSION_2_0)
703     case GL_QUADS:          return AddRaytraceQuadrangleArray      (theSet, theArray.Indices(), theOffset, theCount, theMatID);
704     case GL_QUAD_STRIP:     return AddRaytraceQuadrangleStripArray (theSet, theArray.Indices(), theOffset, theCount, theMatID);
705     case GL_POLYGON:        return AddRaytracePolygonArray         (theSet, theArray.Indices(), theOffset, theCount, theMatID);
706   #endif
707   }
708   return Standard_False;
709 }
710
711 // =======================================================================
712 // function : AddRaytraceTriangleArray
713 // purpose  : Adds OpenGL triangle array to ray-traced scene geometry
714 // =======================================================================
715 Standard_Boolean OpenGl_Workspace::AddRaytraceTriangleArray (OpenGl_TriangleSet&                  theSet,
716                                                              const Handle(Graphic3d_IndexBuffer)& theIndices,
717                                                              Standard_Integer                     theOffset,
718                                                              Standard_Integer                     theCount,
719                                                              Standard_Integer                     theMatID)
720 {
721   if (theCount < 3)
722     return Standard_True;
723
724   theSet.Elements.reserve (theSet.Elements.size() + theCount / 3);
725
726   if (!theIndices.IsNull())
727   {
728     for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; aVert += 3)
729     {
730       theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0),
731                                             theIndices->Index (aVert + 1),
732                                             theIndices->Index (aVert + 2),
733                                             theMatID));
734     }
735   }
736   else
737   {
738     for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; aVert += 3)
739     {
740       theSet.Elements.push_back (BVH_Vec4i (aVert + 0, aVert + 1, aVert + 2,
741                                             theMatID));
742     }
743   }
744
745   return Standard_True;
746 }
747
748 // =======================================================================
749 // function : AddRaytraceTriangleFanArray
750 // purpose  : Adds OpenGL triangle fan array to ray-traced scene geometry
751 // =======================================================================
752 Standard_Boolean OpenGl_Workspace::AddRaytraceTriangleFanArray (OpenGl_TriangleSet&                  theSet,
753                                                                 const Handle(Graphic3d_IndexBuffer)& theIndices,
754                                                                 Standard_Integer                     theOffset,
755                                                                 Standard_Integer                     theCount,
756                                                                 Standard_Integer                     theMatID)
757 {
758   if (theCount < 3)
759     return Standard_True;
760
761   theSet.Elements.reserve (theSet.Elements.size() + theCount - 2);
762
763   if (!theIndices.IsNull())
764   {
765     for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
766     {
767       theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (theOffset),
768                                             theIndices->Index (aVert + 1),
769                                             theIndices->Index (aVert + 2),
770                                             theMatID));
771     }
772   }
773   else
774   {
775     for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
776     {
777       theSet.Elements.push_back (BVH_Vec4i (theOffset,
778                                             aVert + 1,
779                                             aVert + 2,
780                                             theMatID));
781     }
782   }
783
784   return Standard_True;
785 }
786
787 // =======================================================================
788 // function : AddRaytraceTriangleStripArray
789 // purpose  : Adds OpenGL triangle strip array to ray-traced scene geometry
790 // =======================================================================
791 Standard_Boolean OpenGl_Workspace::AddRaytraceTriangleStripArray (OpenGl_TriangleSet&                  theSet,
792                                                                   const Handle(Graphic3d_IndexBuffer)& theIndices,
793                                                                   Standard_Integer                     theOffset,
794                                                                   Standard_Integer                     theCount,
795                                                                   Standard_Integer                     theMatID)
796 {
797   if (theCount < 3)
798     return Standard_True;
799
800   theSet.Elements.reserve (theSet.Elements.size() + theCount - 2);
801
802   if (!theIndices.IsNull())
803   {
804     for (Standard_Integer aVert = theOffset, aCW = 0; aVert < theOffset + theCount - 2; ++aVert, aCW = (aCW + 1) % 2)
805     {
806       theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + aCW ? 1 : 0),
807                                             theIndices->Index (aVert + aCW ? 0 : 1),
808                                             theIndices->Index (aVert + 2),
809                                             theMatID));
810     }
811   }
812   else
813   {
814     for (Standard_Integer aVert = theOffset, aCW = 0; aVert < theOffset + theCount - 2; ++aVert, aCW = (aCW + 1) % 2)
815     {
816       theSet.Elements.push_back (BVH_Vec4i (aVert + aCW ? 1 : 0,
817                                             aVert + aCW ? 0 : 1,
818                                             aVert + 2,
819                                             theMatID));
820     }
821   }
822
823   return Standard_True;
824 }
825
826 // =======================================================================
827 // function : AddRaytraceQuadrangleArray
828 // purpose  : Adds OpenGL quad array to ray-traced scene geometry
829 // =======================================================================
830 Standard_Boolean OpenGl_Workspace::AddRaytraceQuadrangleArray (OpenGl_TriangleSet&                  theSet,
831                                                                const Handle(Graphic3d_IndexBuffer)& theIndices,
832                                                                Standard_Integer                     theOffset,
833                                                                Standard_Integer                     theCount,
834                                                                Standard_Integer                     theMatID)
835 {
836   if (theCount < 4)
837     return Standard_True;
838
839   theSet.Elements.reserve (theSet.Elements.size() + theCount / 2);
840
841   if (!theIndices.IsNull())
842   {
843     for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 4)
844     {
845       theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0),
846                                             theIndices->Index (aVert + 1),
847                                             theIndices->Index (aVert + 2),
848                                             theMatID));
849       theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0),
850                                             theIndices->Index (aVert + 2),
851                                             theIndices->Index (aVert + 3),
852                                             theMatID));
853     }
854   }
855   else
856   {
857     for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 4)
858     {
859       theSet.Elements.push_back (BVH_Vec4i (aVert + 0, aVert + 1, aVert + 2,
860                                             theMatID));
861       theSet.Elements.push_back (BVH_Vec4i (aVert + 0, aVert + 2, aVert + 3,
862                                             theMatID));
863     }
864   }
865
866   return Standard_True;
867 }
868
869 // =======================================================================
870 // function : AddRaytraceQuadrangleStripArray
871 // purpose  : Adds OpenGL quad strip array to ray-traced scene geometry
872 // =======================================================================
873 Standard_Boolean OpenGl_Workspace::AddRaytraceQuadrangleStripArray (OpenGl_TriangleSet&                  theSet,
874                                                                     const Handle(Graphic3d_IndexBuffer)& theIndices,
875                                                                     Standard_Integer                     theOffset,
876                                                                     Standard_Integer                     theCount,
877                                                                     Standard_Integer                     theMatID)
878 {
879   if (theCount < 4)
880     return Standard_True;
881
882   theSet.Elements.reserve (theSet.Elements.size() + 2 * theCount - 6);
883
884   if (!theIndices.IsNull())
885   {
886     for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 2)
887     {
888       theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0),
889                                             theIndices->Index (aVert + 1),
890                                             theIndices->Index (aVert + 2),
891                                             theMatID));
892
893       theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 1),
894                                             theIndices->Index (aVert + 3),
895                                             theIndices->Index (aVert + 2),
896                                             theMatID));
897     }
898   }
899   else
900   {
901     for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 2)
902     {
903       theSet.Elements.push_back (BVH_Vec4i (aVert + 0,
904                                             aVert + 1,
905                                             aVert + 2,
906                                             theMatID));
907
908       theSet.Elements.push_back (BVH_Vec4i (aVert + 1,
909                                             aVert + 3,
910                                             aVert + 2,
911                                             theMatID));
912     }
913   }
914
915   return Standard_True;
916 }
917
918 // =======================================================================
919 // function : AddRaytracePolygonArray
920 // purpose  : Adds OpenGL polygon array to ray-traced scene geometry
921 // =======================================================================
922 Standard_Boolean OpenGl_Workspace::AddRaytracePolygonArray (OpenGl_TriangleSet&                  theSet,
923                                                             const Handle(Graphic3d_IndexBuffer)& theIndices,
924                                                             Standard_Integer                     theOffset,
925                                                             Standard_Integer                     theCount,
926                                                             Standard_Integer                     theMatID)
927 {
928   if (theCount < 3)
929     return Standard_True;
930
931   theSet.Elements.reserve (theSet.Elements.size() + theCount - 2);
932
933   if (!theIndices.IsNull())
934   {
935     for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
936     {
937       theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (theOffset),
938                                             theIndices->Index (aVert + 1),
939                                             theIndices->Index (aVert + 2),
940                                             theMatID));
941     }
942   }
943   else
944   {
945     for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
946     {
947       theSet.Elements.push_back (BVH_Vec4i (theOffset,
948                                             aVert + 1,
949                                             aVert + 2,
950                                             theMatID));
951     }
952   }
953
954   return Standard_True;
955 }
956
957 // =======================================================================
958 // function : UpdateRaytraceLightSources
959 // purpose  : Updates 3D scene light sources for ray-tracing
960 // =======================================================================
961 Standard_Boolean OpenGl_Workspace::UpdateRaytraceLightSources (const OpenGl_Mat4& theInvModelView)
962 {
963   myRaytraceGeometry.Sources.clear();
964
965   myRaytraceGeometry.Ambient = BVH_Vec4f (0.0f, 0.0f, 0.0f, 0.0f);
966
967   for (OpenGl_ListOfLight::Iterator anItl (myView->LightList()); anItl.More(); anItl.Next())
968   {
969     const OpenGl_Light& aLight = anItl.Value();
970
971     if (aLight.Type == Visual3d_TOLS_AMBIENT)
972     {
973       myRaytraceGeometry.Ambient += BVH_Vec4f (aLight.Color.r(),
974                                                aLight.Color.g(),
975                                                aLight.Color.b(),
976                                                0.0f);
977       continue;
978     }
979
980     BVH_Vec4f aDiffuse  (aLight.Color.r(),
981                          aLight.Color.g(),
982                          aLight.Color.b(),
983                          1.0f);
984
985     BVH_Vec4f aPosition (-aLight.Direction.x(),
986                          -aLight.Direction.y(),
987                          -aLight.Direction.z(),
988                          0.0f);
989
990     if (aLight.Type != Visual3d_TOLS_DIRECTIONAL)
991     {
992       aPosition = BVH_Vec4f (aLight.Position.x(),
993                              aLight.Position.y(),
994                              aLight.Position.z(),
995                              1.0f);
996     }
997
998     if (aLight.IsHeadlight)
999     {
1000       aPosition = theInvModelView * aPosition;
1001     }
1002
1003     myRaytraceGeometry.Sources.push_back (OpenGl_RaytraceLight (aDiffuse, aPosition));
1004   }
1005
1006   if (myRaytraceLightSrcTexture.IsNull())  // create light source buffer
1007   {
1008     myRaytraceLightSrcTexture = new OpenGl_TextureBufferArb;
1009
1010     if (!myRaytraceLightSrcTexture->Create (myGlContext))
1011     {
1012 #ifdef RAY_TRACE_PRINT_INFO
1013       std::cout << "Error: Failed to create light source buffer" << std::endl;
1014 #endif
1015       return Standard_False;
1016     }
1017   }
1018   
1019   if (myRaytraceGeometry.Sources.size() != 0)
1020   {
1021     const GLfloat* aDataPtr = myRaytraceGeometry.Sources.front().Packed();
1022     if (!myRaytraceLightSrcTexture->Init (myGlContext, 4, GLsizei (myRaytraceGeometry.Sources.size() * 2), aDataPtr))
1023     {
1024 #ifdef RAY_TRACE_PRINT_INFO
1025       std::cout << "Error: Failed to upload light source buffer" << std::endl;
1026 #endif
1027       return Standard_False;
1028     }
1029   }
1030
1031   return Standard_True;
1032 }
1033
1034 // =======================================================================
1035 // function : UpdateRaytraceEnvironmentMap
1036 // purpose  : Updates environment map for ray-tracing
1037 // =======================================================================
1038 Standard_Boolean OpenGl_Workspace::UpdateRaytraceEnvironmentMap()
1039 {
1040   if (myView.IsNull())
1041     return Standard_False;
1042
1043   if (myViewModificationStatus == myView->ModificationState())
1044     return Standard_True;
1045
1046   for (Standard_Integer anIdx = 0; anIdx < 2; ++anIdx)
1047   {
1048     const Handle(OpenGl_ShaderProgram)& aProgram =
1049       anIdx == 0 ? myRaytraceProgram : myPostFSAAProgram;
1050
1051     if (!aProgram.IsNull())
1052     {
1053       myGlContext->BindProgram (aProgram);
1054
1055       if (!myView->TextureEnv().IsNull() && myView->SurfaceDetail() != Visual3d_TOD_NONE)
1056       {
1057         myView->TextureEnv()->Bind (
1058           myGlContext, GL_TEXTURE0 + OpenGl_RT_EnvironmentMapTexture);
1059
1060         aProgram->SetUniform (myGlContext,
1061           myUniformLocations[anIdx][OpenGl_RT_uEnvMapEnable], 1);
1062       }
1063       else
1064       {
1065         aProgram->SetUniform (myGlContext,
1066           myUniformLocations[anIdx][OpenGl_RT_uEnvMapEnable], 0);
1067       }
1068     }
1069   }
1070
1071   myGlContext->BindProgram (NULL);
1072   myViewModificationStatus = myView->ModificationState();
1073   return Standard_True;
1074 }
1075
1076 // =======================================================================
1077 // function : Source
1078 // purpose  : Returns shader source combined with prefix
1079 // =======================================================================
1080 TCollection_AsciiString OpenGl_Workspace::ShaderSource::Source() const
1081 {
1082   static const TCollection_AsciiString aVersion = "#version 140";
1083
1084   if (myPrefix.IsEmpty())
1085   {
1086     return aVersion + "\n" + mySource;
1087   }
1088
1089   return aVersion + "\n" + myPrefix + "\n" + mySource;
1090 }
1091
1092 // =======================================================================
1093 // function : Load
1094 // purpose  : Loads shader source from specified files
1095 // =======================================================================
1096 void OpenGl_Workspace::ShaderSource::Load (
1097   const TCollection_AsciiString* theFileNames, const Standard_Integer theCount)
1098 {
1099   mySource.Clear();
1100
1101   for (Standard_Integer anIndex = 0; anIndex < theCount; ++anIndex)
1102   {
1103     OSD_File aFile (theFileNames[anIndex]);
1104
1105     Standard_ASSERT_RETURN (aFile.Exists(),
1106       "Error: Failed to find shader source file", /* none */);
1107
1108     aFile.Open (OSD_ReadOnly, OSD_Protection());
1109
1110     TCollection_AsciiString aSource;
1111
1112     Standard_ASSERT_RETURN (aFile.IsOpen(),
1113       "Error: Failed to open shader source file", /* none */);
1114
1115     aFile.Read (aSource, (Standard_Integer) aFile.Size());
1116
1117     if (!aSource.IsEmpty())
1118     {
1119       mySource += TCollection_AsciiString ("\n") + aSource;
1120     }
1121
1122     aFile.Close();
1123   }
1124 }
1125
1126 // =======================================================================
1127 // function : LoadShader
1128 // purpose  : Creates new shader object with specified source
1129 // =======================================================================
1130 Handle(OpenGl_ShaderObject) OpenGl_Workspace::LoadShader (const ShaderSource& theSource, GLenum theType)
1131 {
1132   Handle(OpenGl_ShaderObject) aShader = new OpenGl_ShaderObject (theType);
1133
1134   if (!aShader->Create (myGlContext))
1135   {
1136     const TCollection_ExtendedString aMessage = "Error: Failed to create shader object";
1137       
1138     myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
1139       GL_DEBUG_TYPE_ERROR_ARB, 0, GL_DEBUG_SEVERITY_HIGH_ARB, aMessage);
1140
1141     aShader->Release (myGlContext.operator->());
1142
1143     return Handle(OpenGl_ShaderObject)();
1144   }
1145
1146   if (!aShader->LoadSource (myGlContext, theSource.Source()))
1147   {
1148     const TCollection_ExtendedString aMessage = "Error: Failed to set shader source";
1149       
1150     myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
1151       GL_DEBUG_TYPE_ERROR_ARB, 0, GL_DEBUG_SEVERITY_HIGH_ARB, aMessage);
1152
1153     aShader->Release (myGlContext.operator->());
1154
1155     return Handle(OpenGl_ShaderObject)();
1156   }
1157
1158   TCollection_AsciiString aBuildLog;
1159
1160   if (!aShader->Compile (myGlContext))
1161   {
1162     if (aShader->FetchInfoLog (myGlContext, aBuildLog))
1163     {
1164       const TCollection_ExtendedString aMessage =
1165         TCollection_ExtendedString ("Error: Failed to compile shader object:\n") + aBuildLog;
1166
1167 #ifdef RAY_TRACE_PRINT_INFO
1168       std::cout << aBuildLog << std::endl;
1169 #endif
1170
1171       myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
1172         GL_DEBUG_TYPE_ERROR_ARB, 0, GL_DEBUG_SEVERITY_HIGH_ARB, aMessage);
1173     }
1174     
1175     aShader->Release (myGlContext.operator->());
1176
1177     return Handle(OpenGl_ShaderObject)();
1178   }
1179
1180 #ifdef RAY_TRACE_PRINT_INFO
1181   if (aShader->FetchInfoLog (myGlContext, aBuildLog))
1182   {
1183     if (!aBuildLog.IsEmpty())
1184     {
1185       std::cout << aBuildLog << std::endl;
1186     }
1187     else
1188     {
1189       std::cout << "Info: shader build log is empty" << std::endl;
1190     }
1191   }  
1192 #endif
1193
1194   return aShader;
1195 }
1196
1197 // =======================================================================
1198 // function : SafeFailBack
1199 // purpose  : Performs safe exit when shaders initialization fails
1200 // =======================================================================
1201 Standard_Boolean OpenGl_Workspace::SafeFailBack (const TCollection_ExtendedString& theMessage)
1202 {
1203   myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
1204     GL_DEBUG_TYPE_ERROR_ARB, 0, GL_DEBUG_SEVERITY_HIGH_ARB, theMessage);
1205
1206   myComputeInitStatus = OpenGl_RT_FAIL;
1207
1208   ReleaseRaytraceResources();
1209   
1210   return Standard_False;
1211 }
1212
1213 // =======================================================================
1214 // function : GenerateShaderPrefix
1215 // purpose  : Generates shader prefix based on current ray-tracing options
1216 // =======================================================================
1217 TCollection_AsciiString OpenGl_Workspace::GenerateShaderPrefix()
1218 {
1219   TCollection_AsciiString aPrefixString =
1220     TCollection_AsciiString ("#define STACK_SIZE ") + TCollection_AsciiString (myRaytraceParameters.StackSize) + "\n" +
1221     TCollection_AsciiString ("#define NB_BOUNCES ") + TCollection_AsciiString (myRaytraceParameters.NbBounces);
1222
1223   if (myRaytraceParameters.TransparentShadows)
1224   {
1225     aPrefixString += TCollection_AsciiString ("\n#define TRANSPARENT_SHADOWS");
1226   }
1227
1228   // If OpenGL driver supports bindless textures
1229   // activate texturing in ray-tracing mode
1230   if (myGlContext->arbTexBindless != NULL)
1231   {
1232     aPrefixString += TCollection_AsciiString ("\n#define USE_TEXTURES") +
1233       TCollection_AsciiString ("\n#define MAX_TEX_NUMBER ") + TCollection_AsciiString (OpenGl_RaytraceGeometry::MAX_TEX_NUMBER);
1234   }
1235
1236   return aPrefixString;
1237 }
1238
1239 // =======================================================================
1240 // function : InitRaytraceResources
1241 // purpose  : Initializes OpenGL/GLSL shader programs
1242 // =======================================================================
1243 Standard_Boolean OpenGl_Workspace::InitRaytraceResources (const Graphic3d_CView& theCView)
1244 {
1245   Standard_Boolean aToRebuildShaders = Standard_False;
1246
1247   if (myComputeInitStatus == OpenGl_RT_INIT)
1248   {
1249     if (!myIsRaytraceDataValid)
1250       return Standard_True;
1251
1252     const Standard_Integer aRequiredStackSize =
1253       myRaytraceGeometry.HighLevelTreeDepth() + myRaytraceGeometry.BottomLevelTreeDepth();
1254
1255     if (myRaytraceParameters.StackSize < aRequiredStackSize)
1256     {
1257       myRaytraceParameters.StackSize = Max (aRequiredStackSize, THE_DEFAULT_STACK_SIZE);
1258
1259       aToRebuildShaders = Standard_True;
1260     }
1261     else
1262     {
1263       if (aRequiredStackSize < myRaytraceParameters.StackSize)
1264       {
1265         if (myRaytraceParameters.StackSize > THE_DEFAULT_STACK_SIZE)
1266         {
1267           myRaytraceParameters.StackSize = Max (aRequiredStackSize, THE_DEFAULT_STACK_SIZE);
1268           aToRebuildShaders = Standard_True;
1269         }
1270       }
1271     }
1272
1273     if (theCView.RenderParams.RaytracingDepth != myRaytraceParameters.NbBounces)
1274     {
1275       myRaytraceParameters.NbBounces = theCView.RenderParams.RaytracingDepth;
1276       aToRebuildShaders = Standard_True;
1277     }
1278
1279     if (theCView.RenderParams.IsTransparentShadowEnabled != myRaytraceParameters.TransparentShadows)
1280     {
1281       myRaytraceParameters.TransparentShadows = theCView.RenderParams.IsTransparentShadowEnabled;
1282       aToRebuildShaders = Standard_True;
1283     }
1284
1285     if (aToRebuildShaders)
1286     {
1287 #ifdef RAY_TRACE_PRINT_INFO
1288       std::cout << "Info: Rebuild shaders with stack size: " << myRaytraceParameters.StackSize << std::endl;
1289 #endif
1290
1291       // Change state to force update all uniforms
1292       ++myViewModificationStatus;
1293
1294       TCollection_AsciiString aPrefixString = GenerateShaderPrefix();
1295
1296 #ifdef RAY_TRACE_PRINT_INFO
1297       std::cout << "GLSL prefix string:" << std::endl << aPrefixString << std::endl;
1298 #endif
1299
1300       myRaytraceShaderSource.SetPrefix (aPrefixString);
1301       myPostFSAAShaderSource.SetPrefix (aPrefixString);
1302
1303       if (!myRaytraceShader->LoadSource (myGlContext, myRaytraceShaderSource.Source())
1304        || !myPostFSAAShader->LoadSource (myGlContext, myPostFSAAShaderSource.Source()))
1305       {
1306         return Standard_False;
1307       }
1308
1309       if (!myRaytraceShader->Compile (myGlContext)
1310        || !myPostFSAAShader->Compile (myGlContext))
1311       {
1312         return Standard_False;
1313       }
1314
1315       myRaytraceProgram->SetAttributeName (myGlContext, Graphic3d_TOA_POS, "occVertex");
1316       myPostFSAAProgram->SetAttributeName (myGlContext, Graphic3d_TOA_POS, "occVertex");
1317       if (!myRaytraceProgram->Link (myGlContext)
1318        || !myPostFSAAProgram->Link (myGlContext))
1319       {
1320         return Standard_False;
1321       }
1322     }
1323   }
1324
1325   if (myComputeInitStatus == OpenGl_RT_NONE)
1326   {
1327     if (!myGlContext->IsGlGreaterEqual (3, 1))
1328     {
1329       myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
1330                                 GL_DEBUG_TYPE_ERROR_ARB, 0, GL_DEBUG_SEVERITY_HIGH_ARB,
1331                                 "Ray-tracing requires OpenGL 3.1 and higher");
1332       return Standard_False;
1333     }
1334     else if (!myGlContext->arbTboRGB32)
1335     {
1336       myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
1337                                 GL_DEBUG_TYPE_ERROR_ARB, 0, GL_DEBUG_SEVERITY_HIGH_ARB,
1338                                 "Ray-tracing requires OpenGL 4.0+ or GL_ARB_texture_buffer_object_rgb32 extension");
1339       return Standard_False;
1340     }
1341
1342     myRaytraceParameters.NbBounces = theCView.RenderParams.RaytracingDepth;
1343
1344     TCollection_AsciiString aFolder = Graphic3d_ShaderProgram::ShadersFolder();
1345
1346     if (aFolder.IsEmpty())
1347     {
1348       const TCollection_ExtendedString aMessage = "Failed to locate shaders directory";
1349       
1350       myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
1351         GL_DEBUG_TYPE_ERROR_ARB, 0, GL_DEBUG_SEVERITY_HIGH_ARB, aMessage);
1352       
1353       return Standard_False;
1354     }
1355
1356     if (myIsRaytraceDataValid)
1357     {
1358       myRaytraceParameters.StackSize = Max (THE_DEFAULT_STACK_SIZE,
1359         myRaytraceGeometry.HighLevelTreeDepth() + myRaytraceGeometry.BottomLevelTreeDepth());
1360     }
1361
1362     TCollection_AsciiString aPrefixString  = GenerateShaderPrefix();
1363
1364 #ifdef RAY_TRACE_PRINT_INFO
1365     std::cout << "GLSL prefix string:" << std::endl << aPrefixString << std::endl;
1366 #endif
1367
1368     {
1369       Handle(OpenGl_ShaderObject) aBasicVertShader = LoadShader (
1370         ShaderSource (aFolder + "/RaytraceBase.vs"), GL_VERTEX_SHADER);
1371
1372       if (aBasicVertShader.IsNull())
1373       {
1374         return SafeFailBack ("Failed to set vertex shader source");
1375       }
1376
1377       TCollection_AsciiString aFiles[] = { aFolder + "/RaytraceBase.fs", aFolder + "/RaytraceRender.fs" };
1378
1379       myRaytraceShaderSource.Load (aFiles, 2);
1380
1381       myRaytraceShaderSource.SetPrefix (aPrefixString);
1382
1383       myRaytraceShader = LoadShader (myRaytraceShaderSource, GL_FRAGMENT_SHADER);
1384
1385       if (myRaytraceShader.IsNull())
1386       {
1387         aBasicVertShader->Release (myGlContext.operator->());
1388
1389         return SafeFailBack ("Failed to set ray-trace fragment shader source");
1390       }
1391
1392       myRaytraceProgram = new OpenGl_ShaderProgram;
1393
1394       if (!myRaytraceProgram->Create (myGlContext))
1395       {
1396         aBasicVertShader->Release (myGlContext.operator->());
1397
1398         return SafeFailBack ("Failed to create ray-trace shader program");
1399       }
1400
1401       if (!myRaytraceProgram->AttachShader (myGlContext, aBasicVertShader)
1402        || !myRaytraceProgram->AttachShader (myGlContext, myRaytraceShader))
1403       {
1404         aBasicVertShader->Release (myGlContext.operator->());
1405
1406         return SafeFailBack ("Failed to attach ray-trace shader objects");
1407       }
1408
1409       myRaytraceProgram->SetAttributeName (myGlContext, Graphic3d_TOA_POS, "occVertex");
1410       if (!myRaytraceProgram->Link (myGlContext))
1411       {
1412         TCollection_AsciiString aLinkLog;
1413
1414         if (myRaytraceProgram->FetchInfoLog (myGlContext, aLinkLog))
1415         {
1416   #ifdef RAY_TRACE_PRINT_INFO
1417           std::cout << aLinkLog << std::endl;
1418   #endif
1419         }
1420
1421         return SafeFailBack ("Failed to link ray-trace shader program");
1422       }
1423     }
1424
1425     {
1426       Handle(OpenGl_ShaderObject) aBasicVertShader = LoadShader (
1427         ShaderSource (aFolder + "/RaytraceBase.vs"), GL_VERTEX_SHADER);
1428
1429       if (aBasicVertShader.IsNull())
1430       {
1431         return SafeFailBack ("Failed to set vertex shader source");
1432       }
1433
1434       TCollection_AsciiString aFiles[] = { aFolder + "/RaytraceBase.fs", aFolder + "/RaytraceSmooth.fs" };
1435
1436       myPostFSAAShaderSource.Load (aFiles, 2);
1437
1438       myPostFSAAShaderSource.SetPrefix (aPrefixString);
1439     
1440       myPostFSAAShader = LoadShader (myPostFSAAShaderSource, GL_FRAGMENT_SHADER);
1441
1442       if (myPostFSAAShader.IsNull())
1443       {
1444         aBasicVertShader->Release (myGlContext.operator->());
1445
1446         return SafeFailBack ("Failed to set FSAA fragment shader source");
1447       }
1448
1449       myPostFSAAProgram = new OpenGl_ShaderProgram;
1450
1451       if (!myPostFSAAProgram->Create (myGlContext))
1452       {
1453         aBasicVertShader->Release (myGlContext.operator->());
1454
1455         return SafeFailBack ("Failed to create FSAA shader program");
1456       }
1457
1458       if (!myPostFSAAProgram->AttachShader (myGlContext, aBasicVertShader)
1459        || !myPostFSAAProgram->AttachShader (myGlContext, myPostFSAAShader))
1460       {
1461         aBasicVertShader->Release (myGlContext.operator->());
1462
1463         return SafeFailBack ("Failed to attach FSAA shader objects");
1464       }
1465
1466       myPostFSAAProgram->SetAttributeName (myGlContext, Graphic3d_TOA_POS, "occVertex");
1467       if (!myPostFSAAProgram->Link (myGlContext))
1468       {
1469         TCollection_AsciiString aLinkLog;
1470
1471         if (myPostFSAAProgram->FetchInfoLog (myGlContext, aLinkLog))
1472         {
1473   #ifdef RAY_TRACE_PRINT_INFO
1474           std::cout << aLinkLog << std::endl;
1475   #endif
1476         }
1477       
1478         return SafeFailBack ("Failed to link FSAA shader program");
1479       }
1480     }
1481   }
1482
1483   if (myComputeInitStatus == OpenGl_RT_NONE || aToRebuildShaders)
1484   {
1485     for (Standard_Integer anIndex = 0; anIndex < 2; ++anIndex)
1486     {
1487       Handle(OpenGl_ShaderProgram)& aShaderProgram =
1488         (anIndex == 0) ? myRaytraceProgram : myPostFSAAProgram;
1489
1490       myGlContext->BindProgram (aShaderProgram);
1491
1492       aShaderProgram->SetSampler (myGlContext,
1493         "uSceneMinPointTexture", OpenGl_RT_SceneMinPointTexture);
1494       aShaderProgram->SetSampler (myGlContext,
1495         "uSceneMaxPointTexture", OpenGl_RT_SceneMaxPointTexture);
1496       aShaderProgram->SetSampler (myGlContext,
1497         "uSceneNodeInfoTexture", OpenGl_RT_SceneNodeInfoTexture);
1498       aShaderProgram->SetSampler (myGlContext,
1499         "uGeometryVertexTexture", OpenGl_RT_GeometryVertexTexture);
1500       aShaderProgram->SetSampler (myGlContext,
1501         "uGeometryNormalTexture", OpenGl_RT_GeometryNormalTexture);
1502       aShaderProgram->SetSampler (myGlContext,
1503         "uGeometryTexCrdTexture", OpenGl_RT_GeometryTexCrdTexture);
1504       aShaderProgram->SetSampler (myGlContext,
1505         "uGeometryTriangTexture", OpenGl_RT_GeometryTriangTexture);
1506       aShaderProgram->SetSampler (myGlContext, 
1507         "uSceneTransformTexture", OpenGl_RT_SceneTransformTexture);
1508       aShaderProgram->SetSampler (myGlContext,
1509         "uEnvironmentMapTexture", OpenGl_RT_EnvironmentMapTexture);
1510       aShaderProgram->SetSampler (myGlContext,
1511         "uRaytraceMaterialTexture", OpenGl_RT_RaytraceMaterialTexture);
1512       aShaderProgram->SetSampler (myGlContext,
1513         "uRaytraceLightSrcTexture", OpenGl_RT_RaytraceLightSrcTexture);
1514
1515       aShaderProgram->SetSampler (myGlContext,
1516         "uOpenGlColorTexture", OpenGl_RT_OpenGlColorTexture);
1517       aShaderProgram->SetSampler (myGlContext,
1518         "uOpenGlDepthTexture", OpenGl_RT_OpenGlDepthTexture);
1519
1520       if (anIndex == 1)
1521       {
1522         aShaderProgram->SetSampler (myGlContext,
1523           "uFSAAInputTexture", OpenGl_RT_FSAAInputTexture);
1524       }
1525
1526       myUniformLocations[anIndex][OpenGl_RT_aPosition] =
1527         aShaderProgram->GetAttributeLocation (myGlContext, "occVertex");
1528
1529       myUniformLocations[anIndex][OpenGl_RT_uOriginLB] =
1530         aShaderProgram->GetUniformLocation (myGlContext, "uOriginLB");
1531       myUniformLocations[anIndex][OpenGl_RT_uOriginRB] =
1532         aShaderProgram->GetUniformLocation (myGlContext, "uOriginRB");
1533       myUniformLocations[anIndex][OpenGl_RT_uOriginLT] =
1534         aShaderProgram->GetUniformLocation (myGlContext, "uOriginLT");
1535       myUniformLocations[anIndex][OpenGl_RT_uOriginRT] =
1536         aShaderProgram->GetUniformLocation (myGlContext, "uOriginRT");
1537       myUniformLocations[anIndex][OpenGl_RT_uDirectLB] =
1538         aShaderProgram->GetUniformLocation (myGlContext, "uDirectLB");
1539       myUniformLocations[anIndex][OpenGl_RT_uDirectRB] =
1540         aShaderProgram->GetUniformLocation (myGlContext, "uDirectRB");
1541       myUniformLocations[anIndex][OpenGl_RT_uDirectLT] =
1542         aShaderProgram->GetUniformLocation (myGlContext, "uDirectLT");
1543       myUniformLocations[anIndex][OpenGl_RT_uDirectRT] =
1544         aShaderProgram->GetUniformLocation (myGlContext, "uDirectRT");
1545       myUniformLocations[anIndex][OpenGl_RT_uUnviewMat] =
1546         aShaderProgram->GetUniformLocation (myGlContext, "uUnviewMat");
1547
1548       myUniformLocations[anIndex][OpenGl_RT_uSceneRad] =
1549         aShaderProgram->GetUniformLocation (myGlContext, "uSceneRadius");
1550       myUniformLocations[anIndex][OpenGl_RT_uSceneEps] =
1551         aShaderProgram->GetUniformLocation (myGlContext, "uSceneEpsilon");
1552       myUniformLocations[anIndex][OpenGl_RT_uLightCount] =
1553         aShaderProgram->GetUniformLocation (myGlContext, "uLightCount");
1554       myUniformLocations[anIndex][OpenGl_RT_uLightAmbnt] =
1555         aShaderProgram->GetUniformLocation (myGlContext, "uGlobalAmbient");
1556
1557       myUniformLocations[anIndex][OpenGl_RT_uOffsetX] =
1558         aShaderProgram->GetUniformLocation (myGlContext, "uOffsetX");
1559       myUniformLocations[anIndex][OpenGl_RT_uOffsetY] =
1560         aShaderProgram->GetUniformLocation (myGlContext, "uOffsetY");
1561       myUniformLocations[anIndex][OpenGl_RT_uSamples] =
1562         aShaderProgram->GetUniformLocation (myGlContext, "uSamples");
1563       myUniformLocations[anIndex][OpenGl_RT_uWinSizeX] =
1564         aShaderProgram->GetUniformLocation (myGlContext, "uWinSizeX");
1565       myUniformLocations[anIndex][OpenGl_RT_uWinSizeY] =
1566         aShaderProgram->GetUniformLocation (myGlContext, "uWinSizeY");
1567
1568       myUniformLocations[anIndex][OpenGl_RT_uTextures] =
1569         aShaderProgram->GetUniformLocation (myGlContext, "uTextureSamplers");
1570
1571       myUniformLocations[anIndex][OpenGl_RT_uShadEnabled] =
1572         aShaderProgram->GetUniformLocation (myGlContext, "uShadowsEnable");
1573       myUniformLocations[anIndex][OpenGl_RT_uReflEnabled] =
1574         aShaderProgram->GetUniformLocation (myGlContext, "uReflectionsEnable");
1575       myUniformLocations[anIndex][OpenGl_RT_uEnvMapEnable] =
1576         aShaderProgram->GetUniformLocation (myGlContext, "uEnvironmentEnable");
1577     }
1578
1579     myGlContext->BindProgram (NULL);
1580   }
1581
1582   if (myComputeInitStatus != OpenGl_RT_NONE)
1583   {
1584     return myComputeInitStatus == OpenGl_RT_INIT;
1585   }
1586
1587   if (myRaytraceFBO1.IsNull())
1588   {
1589     myRaytraceFBO1 = new OpenGl_FrameBuffer;
1590   }
1591
1592   if (myRaytraceFBO2.IsNull())
1593   {
1594     myRaytraceFBO2 = new OpenGl_FrameBuffer;
1595   }
1596
1597   const GLfloat aVertices[] = { -1.f, -1.f,  0.f,
1598                                 -1.f,  1.f,  0.f,
1599                                  1.f,  1.f,  0.f,
1600                                  1.f,  1.f,  0.f,
1601                                  1.f, -1.f,  0.f,
1602                                 -1.f, -1.f,  0.f };
1603
1604   myRaytraceScreenQuad.Init (myGlContext, 3, 6, aVertices);
1605
1606   myComputeInitStatus = OpenGl_RT_INIT; // initialized in normal way
1607
1608   return Standard_True;
1609 }
1610
1611 // =======================================================================
1612 // function : NullifyResource
1613 // purpose  :
1614 // =======================================================================
1615 inline void NullifyResource (const Handle(OpenGl_Context)& theContext,
1616                              Handle(OpenGl_Resource)&      theResource)
1617 {
1618   if (!theResource.IsNull())
1619   {
1620     theResource->Release (theContext.operator->());
1621     theResource.Nullify();
1622   }
1623 }
1624
1625 // =======================================================================
1626 // function : ReleaseRaytraceResources
1627 // purpose  : Releases OpenGL/GLSL shader programs
1628 // =======================================================================
1629 void OpenGl_Workspace::ReleaseRaytraceResources()
1630 {
1631   NullifyResource (myGlContext, myOpenGlFBO);
1632   NullifyResource (myGlContext, myRaytraceFBO1);
1633   NullifyResource (myGlContext, myRaytraceFBO2);
1634
1635   NullifyResource (myGlContext, myRaytraceShader);
1636   NullifyResource (myGlContext, myPostFSAAShader);
1637
1638   NullifyResource (myGlContext, myRaytraceProgram);
1639   NullifyResource (myGlContext, myPostFSAAProgram);
1640
1641   NullifyResource (myGlContext, mySceneNodeInfoTexture);
1642   NullifyResource (myGlContext, mySceneMinPointTexture);
1643   NullifyResource (myGlContext, mySceneMaxPointTexture);
1644
1645   NullifyResource (myGlContext, myGeometryVertexTexture);
1646   NullifyResource (myGlContext, myGeometryNormalTexture);
1647   NullifyResource (myGlContext, myGeometryTexCrdTexture);
1648   NullifyResource (myGlContext, myGeometryTriangTexture);
1649   NullifyResource (myGlContext, mySceneTransformTexture);
1650
1651   NullifyResource (myGlContext, myRaytraceLightSrcTexture);
1652   NullifyResource (myGlContext, myRaytraceMaterialTexture);
1653
1654   if (myRaytraceScreenQuad.IsValid())
1655     myRaytraceScreenQuad.Release (myGlContext.operator->());
1656 }
1657
1658 // =======================================================================
1659 // function : UploadRaytraceData
1660 // purpose  : Uploads ray-trace data to the GPU
1661 // =======================================================================
1662 Standard_Boolean OpenGl_Workspace::UploadRaytraceData()
1663 {
1664   if (!myGlContext->IsGlGreaterEqual (3, 1))
1665   {
1666 #ifdef RAY_TRACE_PRINT_INFO
1667     std::cout << "Error: OpenGL version is less than 3.1" << std::endl;
1668 #endif
1669     return Standard_False;
1670   }
1671
1672   /////////////////////////////////////////////////////////////////////////////
1673   // Prepare OpenGL textures
1674
1675   if (myGlContext->arbTexBindless != NULL)
1676   {
1677     // If OpenGL driver supports bindless textures we need
1678     // to get unique 64- bit handles for using on the GPU
1679     if (!myRaytraceGeometry.UpdateTextureHandles (myGlContext))
1680     {
1681 #ifdef RAY_TRACE_PRINT_INFO
1682       std::cout << "Error: Failed to get OpenGL texture handles" << std::endl;
1683 #endif
1684       return Standard_False;
1685     }
1686   }
1687
1688   /////////////////////////////////////////////////////////////////////////////
1689   // Create OpenGL BVH buffers
1690
1691   if (mySceneNodeInfoTexture.IsNull())  // create scene BVH buffers
1692   {
1693     mySceneNodeInfoTexture  = new OpenGl_TextureBufferArb;
1694     mySceneMinPointTexture  = new OpenGl_TextureBufferArb;
1695     mySceneMaxPointTexture  = new OpenGl_TextureBufferArb;
1696     mySceneTransformTexture = new OpenGl_TextureBufferArb;
1697
1698     if (!mySceneNodeInfoTexture->Create  (myGlContext)
1699      || !mySceneMinPointTexture->Create  (myGlContext)
1700      || !mySceneMaxPointTexture->Create  (myGlContext)
1701      || !mySceneTransformTexture->Create (myGlContext))
1702     {
1703 #ifdef RAY_TRACE_PRINT_INFO
1704       std::cout << "Error: Failed to create scene BVH buffers" << std::endl;
1705 #endif
1706       return Standard_False;
1707     }
1708   }
1709
1710   if  (myGeometryVertexTexture.IsNull())  // create geometry buffers
1711   {
1712     myGeometryVertexTexture = new OpenGl_TextureBufferArb;
1713     myGeometryNormalTexture = new OpenGl_TextureBufferArb;
1714     myGeometryTexCrdTexture = new OpenGl_TextureBufferArb;
1715     myGeometryTriangTexture = new OpenGl_TextureBufferArb;
1716
1717     if (!myGeometryVertexTexture->Create (myGlContext)
1718      || !myGeometryNormalTexture->Create (myGlContext)
1719      || !myGeometryTexCrdTexture->Create (myGlContext)
1720      || !myGeometryTriangTexture->Create (myGlContext))
1721     {
1722 #ifdef RAY_TRACE_PRINT_INFO
1723       std::cout << "Error: Failed to create buffers for triangulation data" << std::endl;
1724 #endif
1725       return Standard_False;
1726     }
1727   }
1728
1729   if (myRaytraceMaterialTexture.IsNull()) // create material buffer
1730   {
1731     myRaytraceMaterialTexture = new OpenGl_TextureBufferArb;
1732
1733     if (!myRaytraceMaterialTexture->Create (myGlContext))
1734     {
1735 #ifdef RAY_TRACE_PRINT_INFO
1736       std::cout << "Error: Failed to create buffers for material data" << std::endl;
1737 #endif
1738       return Standard_False;
1739     }
1740   }
1741   
1742   /////////////////////////////////////////////////////////////////////////////
1743   // Write transform buffer
1744
1745   BVH_Mat4f* aNodeTransforms = new BVH_Mat4f[myRaytraceGeometry.Size()];
1746
1747   bool aResult = true;
1748
1749   for (Standard_Integer anElemIndex = 0; anElemIndex < myRaytraceGeometry.Size(); ++anElemIndex)
1750   {
1751     OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
1752       myRaytraceGeometry.Objects().ChangeValue (anElemIndex).operator->());
1753
1754     const BVH_Transform<Standard_ShortReal, 4>* aTransform = 
1755       dynamic_cast<const BVH_Transform<Standard_ShortReal, 4>* > (aTriangleSet->Properties().operator->());
1756
1757     Standard_ASSERT_RETURN (aTransform != NULL,
1758       "OpenGl_TriangleSet does not contain transform", Standard_False);
1759
1760     aNodeTransforms[anElemIndex] = aTransform->Inversed();
1761   }
1762
1763   aResult &= mySceneTransformTexture->Init (myGlContext, 4,
1764     myRaytraceGeometry.Size() * 4, reinterpret_cast<const GLfloat*> (aNodeTransforms));
1765
1766   delete [] aNodeTransforms;
1767
1768   /////////////////////////////////////////////////////////////////////////////
1769   // Write geometry and bottom-level BVH buffers
1770
1771   Standard_Size aTotalVerticesNb = 0;
1772   Standard_Size aTotalElementsNb = 0;
1773   Standard_Size aTotalBVHNodesNb = 0;
1774
1775   for (Standard_Integer anElemIndex = 0; anElemIndex < myRaytraceGeometry.Size(); ++anElemIndex)
1776   {
1777     OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
1778       myRaytraceGeometry.Objects().ChangeValue (anElemIndex).operator->());
1779
1780     Standard_ASSERT_RETURN (aTriangleSet != NULL,
1781       "Error: Failed to get triangulation of OpenGL element", Standard_False);
1782
1783     aTotalVerticesNb += aTriangleSet->Vertices.size();
1784     aTotalElementsNb += aTriangleSet->Elements.size();
1785
1786     Standard_ASSERT_RETURN (!aTriangleSet->BVH().IsNull(),
1787       "Error: Failed to get bottom-level BVH of OpenGL element", Standard_False);
1788
1789     aTotalBVHNodesNb += aTriangleSet->BVH()->NodeInfoBuffer().size();
1790   }
1791
1792   aTotalBVHNodesNb += myRaytraceGeometry.BVH()->NodeInfoBuffer().size();
1793
1794   if (aTotalBVHNodesNb != 0)
1795   {
1796     aResult &= mySceneNodeInfoTexture->Init (
1797       myGlContext, 4, GLsizei (aTotalBVHNodesNb), static_cast<const GLuint*>  (NULL));
1798     aResult &= mySceneMinPointTexture->Init (
1799       myGlContext, 3, GLsizei (aTotalBVHNodesNb), static_cast<const GLfloat*> (NULL));
1800     aResult &= mySceneMaxPointTexture->Init (
1801       myGlContext, 3, GLsizei (aTotalBVHNodesNb), static_cast<const GLfloat*> (NULL));
1802   }
1803
1804   if (!aResult)
1805   {
1806 #ifdef RAY_TRACE_PRINT_INFO
1807     std::cout << "Error: Failed to upload buffers for bottom-level scene BVH" << std::endl;
1808 #endif
1809     return Standard_False;
1810   }
1811
1812   if (aTotalElementsNb != 0)
1813   {
1814     aResult &= myGeometryTriangTexture->Init (
1815       myGlContext, 4, GLsizei (aTotalElementsNb), static_cast<const GLuint*> (NULL));
1816   }
1817
1818   if (aTotalVerticesNb != 0)
1819   {
1820     aResult &= myGeometryVertexTexture->Init (
1821       myGlContext, 3, GLsizei (aTotalVerticesNb), static_cast<const GLfloat*> (NULL));
1822     aResult &= myGeometryNormalTexture->Init (
1823       myGlContext, 3, GLsizei (aTotalVerticesNb), static_cast<const GLfloat*> (NULL));
1824     aResult &= myGeometryTexCrdTexture->Init (
1825       myGlContext, 2, GLsizei (aTotalVerticesNb), static_cast<const GLfloat*> (NULL));
1826   }
1827
1828   if (!aResult)
1829   {
1830 #ifdef RAY_TRACE_PRINT_INFO
1831     std::cout << "Error: Failed to upload buffers for scene geometry" << std::endl;
1832 #endif
1833     return Standard_False;
1834   }
1835
1836   const NCollection_Handle<BVH_Tree<Standard_ShortReal, 3> >& aBVH = myRaytraceGeometry.BVH();
1837
1838   aResult &= mySceneNodeInfoTexture->SubData (myGlContext, 0, aBVH->Length(),
1839     reinterpret_cast<const GLuint*> (&aBVH->NodeInfoBuffer().front()));
1840   aResult &= mySceneMinPointTexture->SubData (myGlContext, 0, aBVH->Length(),
1841     reinterpret_cast<const GLfloat*> (&aBVH->MinPointBuffer().front()));
1842   aResult &= mySceneMaxPointTexture->SubData (myGlContext, 0, aBVH->Length(),
1843     reinterpret_cast<const GLfloat*> (&aBVH->MaxPointBuffer().front()));
1844
1845   for (Standard_Integer aNodeIdx = 0; aNodeIdx < aBVH->Length(); ++aNodeIdx)
1846   {
1847     if (!aBVH->IsOuter (aNodeIdx))
1848       continue;
1849
1850     OpenGl_TriangleSet* aTriangleSet = myRaytraceGeometry.TriangleSet (aNodeIdx);
1851
1852     Standard_ASSERT_RETURN (aTriangleSet != NULL,
1853       "Error: Failed to get triangulation of OpenGL element", Standard_False);
1854
1855     Standard_Integer aBVHOffset = myRaytraceGeometry.AccelerationOffset (aNodeIdx);
1856
1857     Standard_ASSERT_RETURN (aBVHOffset != OpenGl_RaytraceGeometry::INVALID_OFFSET,
1858       "Error: Failed to get offset for bottom-level BVH", Standard_False);
1859
1860     const Standard_Integer aBvhBuffersSize = aTriangleSet->BVH()->Length();
1861
1862     if (aBvhBuffersSize != 0)
1863     {
1864       aResult &= mySceneNodeInfoTexture->SubData (myGlContext, aBVHOffset, aBvhBuffersSize,
1865                                                    reinterpret_cast<const GLuint*> (&aTriangleSet->BVH()->NodeInfoBuffer().front()));
1866       aResult &= mySceneMinPointTexture->SubData (myGlContext, aBVHOffset, aBvhBuffersSize,
1867                                                    reinterpret_cast<const GLfloat*> (&aTriangleSet->BVH()->MinPointBuffer().front()));
1868       aResult &= mySceneMaxPointTexture->SubData (myGlContext, aBVHOffset, aBvhBuffersSize,
1869                                                    reinterpret_cast<const GLfloat*> (&aTriangleSet->BVH()->MaxPointBuffer().front()));
1870       if (!aResult)
1871       {
1872 #ifdef RAY_TRACE_PRINT_INFO
1873         std::cout << "Error: Failed to upload buffers for bottom-level scene BVHs" << std::endl;
1874 #endif
1875         return Standard_False;
1876       }
1877     }
1878
1879     const Standard_Integer aVerticesOffset = myRaytraceGeometry.VerticesOffset (aNodeIdx);
1880
1881     Standard_ASSERT_RETURN (aVerticesOffset != OpenGl_RaytraceGeometry::INVALID_OFFSET,
1882       "Error: Failed to get offset for triangulation vertices of OpenGL element", Standard_False);
1883
1884     if (!aTriangleSet->Vertices.empty())
1885     {
1886       aResult &= myGeometryNormalTexture->SubData (myGlContext, aVerticesOffset, GLsizei (aTriangleSet->Normals.size()),
1887                                                    reinterpret_cast<const GLfloat*> (&aTriangleSet->Normals.front()));
1888       aResult &= myGeometryTexCrdTexture->SubData (myGlContext, aVerticesOffset, GLsizei (aTriangleSet->TexCrds.size()),
1889                                                    reinterpret_cast<const GLfloat*> (&aTriangleSet->TexCrds.front()));
1890       aResult &= myGeometryVertexTexture->SubData (myGlContext, aVerticesOffset, GLsizei (aTriangleSet->Vertices.size()),
1891                                                    reinterpret_cast<const GLfloat*> (&aTriangleSet->Vertices.front()));
1892     }
1893
1894     const Standard_Integer anElementsOffset = myRaytraceGeometry.ElementsOffset (aNodeIdx);
1895
1896     Standard_ASSERT_RETURN (anElementsOffset != OpenGl_RaytraceGeometry::INVALID_OFFSET,
1897       "Error: Failed to get offset for triangulation elements of OpenGL element", Standard_False);
1898
1899     if (!aTriangleSet->Elements.empty())
1900     {
1901       aResult &= myGeometryTriangTexture->SubData (myGlContext, anElementsOffset, GLsizei (aTriangleSet->Elements.size()),
1902                                                    reinterpret_cast<const GLuint*> (&aTriangleSet->Elements.front()));
1903     }
1904
1905     if (!aResult)
1906     {
1907 #ifdef RAY_TRACE_PRINT_INFO
1908       std::cout << "Error: Failed to upload triangulation buffers for OpenGL element" << std::endl;
1909 #endif
1910       return Standard_False;
1911     }
1912   }
1913
1914   /////////////////////////////////////////////////////////////////////////////
1915   // Write material buffer
1916
1917   if (myRaytraceGeometry.Materials.size() != 0)
1918   {
1919     aResult &= myRaytraceMaterialTexture->Init (myGlContext, 4,
1920       GLsizei (myRaytraceGeometry.Materials.size() * 11),  myRaytraceGeometry.Materials.front().Packed());
1921
1922     if (!aResult)
1923     {
1924 #ifdef RAY_TRACE_PRINT_INFO
1925       std::cout << "Error: Failed to upload material buffer" << std::endl;
1926 #endif
1927       return Standard_False;
1928     }
1929   }
1930
1931   myIsRaytraceDataValid = myRaytraceGeometry.Objects().Size() != 0;
1932
1933 #ifdef RAY_TRACE_PRINT_INFO
1934
1935   Standard_ShortReal aMemUsed = 0.f;
1936
1937   for (Standard_Integer anElemIdx = 0; anElemIdx < myRaytraceGeometry.Size(); ++anElemIdx)
1938   {
1939     OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
1940       myRaytraceGeometry.Objects().ChangeValue (anElemIdx).operator->());
1941
1942     aMemUsed += static_cast<Standard_ShortReal> (
1943       aTriangleSet->Vertices.size() * sizeof (BVH_Vec3f));
1944     aMemUsed += static_cast<Standard_ShortReal> (
1945       aTriangleSet->Normals.size() * sizeof (BVH_Vec3f));
1946     aMemUsed += static_cast<Standard_ShortReal> (
1947       aTriangleSet->TexCrds.size() * sizeof (BVH_Vec2f));
1948     aMemUsed += static_cast<Standard_ShortReal> (
1949       aTriangleSet->Elements.size() * sizeof (BVH_Vec4i));
1950
1951     aMemUsed += static_cast<Standard_ShortReal> (
1952       aTriangleSet->BVH()->NodeInfoBuffer().size() * sizeof (BVH_Vec4i));
1953     aMemUsed += static_cast<Standard_ShortReal> (
1954       aTriangleSet->BVH()->MinPointBuffer().size() * sizeof (BVH_Vec3f));
1955     aMemUsed += static_cast<Standard_ShortReal> (
1956       aTriangleSet->BVH()->MaxPointBuffer().size() * sizeof (BVH_Vec3f));
1957   }
1958
1959   aMemUsed += static_cast<Standard_ShortReal> (
1960     myRaytraceGeometry.BVH()->NodeInfoBuffer().size() * sizeof (BVH_Vec4i));
1961   aMemUsed += static_cast<Standard_ShortReal> (
1962     myRaytraceGeometry.BVH()->MinPointBuffer().size() * sizeof (BVH_Vec3f));
1963   aMemUsed += static_cast<Standard_ShortReal> (
1964     myRaytraceGeometry.BVH()->MaxPointBuffer().size() * sizeof (BVH_Vec3f));
1965
1966   std::cout << "GPU Memory Used (MB): ~" << aMemUsed / 1048576 << std::endl;
1967
1968 #endif
1969
1970   return aResult;
1971 }
1972
1973 // =======================================================================
1974 // function : ResizeRaytraceBuffers
1975 // purpose  : Resizes OpenGL frame buffers
1976 // =======================================================================
1977 Standard_Boolean OpenGl_Workspace::ResizeRaytraceBuffers (const Standard_Integer theSizeX,
1978                                                           const Standard_Integer theSizeY)
1979 {
1980   if (myRaytraceFBO1->GetVPSizeX() != theSizeX
1981    || myRaytraceFBO1->GetVPSizeY() != theSizeY)
1982   {
1983     myRaytraceFBO1->Init (myGlContext, theSizeX, theSizeY);
1984     myRaytraceFBO2->Init (myGlContext, theSizeX, theSizeY);
1985   }
1986
1987   return Standard_True;
1988 }
1989
1990 // =======================================================================
1991 // function : UpdateCamera
1992 // purpose  : Generates viewing rays for corners of screen quad
1993 // =======================================================================
1994 void OpenGl_Workspace::UpdateCamera (const OpenGl_Mat4& theOrientation,
1995                                      const OpenGl_Mat4& theViewMapping,
1996                                      OpenGl_Vec3        theOrigins[4],
1997                                      OpenGl_Vec3        theDirects[4],
1998                                      OpenGl_Mat4&       theInvModelProj)
1999 {
2000   // compute inverse model-view-projection matrix
2001   (theViewMapping * theOrientation).Inverted (theInvModelProj);
2002
2003   Standard_Integer aOriginIndex = 0;
2004   Standard_Integer aDirectIndex = 0;
2005
2006   for (Standard_Integer aY = -1; aY <= 1; aY += 2)
2007   {
2008     for (Standard_Integer aX = -1; aX <= 1; aX += 2)
2009     {
2010       OpenGl_Vec4 aOrigin (GLfloat(aX),
2011                            GLfloat(aY),
2012                           -1.0f,
2013                            1.0f);
2014
2015       aOrigin = theInvModelProj * aOrigin;
2016
2017       aOrigin.x() = aOrigin.x() / aOrigin.w();
2018       aOrigin.y() = aOrigin.y() / aOrigin.w();
2019       aOrigin.z() = aOrigin.z() / aOrigin.w();
2020
2021       OpenGl_Vec4 aDirect (GLfloat(aX),
2022                            GLfloat(aY),
2023                            1.0f,
2024                            1.0f);
2025
2026       aDirect = theInvModelProj * aDirect;
2027
2028       aDirect.x() = aDirect.x() / aDirect.w();
2029       aDirect.y() = aDirect.y() / aDirect.w();
2030       aDirect.z() = aDirect.z() / aDirect.w();
2031
2032       aDirect = aDirect - aOrigin;
2033
2034       GLdouble aInvLen = 1.0 / sqrt (aDirect.x() * aDirect.x() +
2035                                      aDirect.y() * aDirect.y() +
2036                                      aDirect.z() * aDirect.z());
2037
2038       theOrigins[aOriginIndex++] = OpenGl_Vec3 (static_cast<GLfloat> (aOrigin.x()),
2039                                                 static_cast<GLfloat> (aOrigin.y()),
2040                                                 static_cast<GLfloat> (aOrigin.z()));
2041
2042       theDirects[aDirectIndex++] = OpenGl_Vec3 (static_cast<GLfloat> (aDirect.x() * aInvLen),
2043                                                 static_cast<GLfloat> (aDirect.y() * aInvLen),
2044                                                 static_cast<GLfloat> (aDirect.z() * aInvLen));
2045     }
2046   }
2047 }
2048
2049 // =======================================================================
2050 // function : SetUniformState
2051 // purpose  : Sets uniform state for the given ray-tracing shader program
2052 // =======================================================================
2053 Standard_Boolean OpenGl_Workspace::SetUniformState (const Graphic3d_CView&        theCView,
2054                                                     const Standard_Integer        theSizeX,
2055                                                     const Standard_Integer        theSizeY,
2056                                                     const OpenGl_Vec3*            theOrigins,
2057                                                     const OpenGl_Vec3*            theDirects,
2058                                                     const OpenGl_Mat4&            theUnviewMat,
2059                                                     const Standard_Integer        theProgramIndex,
2060                                                     Handle(OpenGl_ShaderProgram)& theRaytraceProgram)
2061 {
2062   if (theRaytraceProgram.IsNull())
2063   {
2064     return Standard_False;
2065   }
2066
2067   Standard_Integer aLightSourceBufferSize =
2068     static_cast<Standard_Integer> (myRaytraceGeometry.Sources.size());
2069
2070   Standard_Boolean aResult = Standard_True;
2071
2072   // Set camera state
2073   aResult &= theRaytraceProgram->SetUniform (myGlContext,
2074     myUniformLocations[theProgramIndex][OpenGl_RT_uOriginLB], theOrigins[0]);
2075   aResult &= theRaytraceProgram->SetUniform (myGlContext,
2076     myUniformLocations[theProgramIndex][OpenGl_RT_uOriginRB], theOrigins[1]);
2077   aResult &= theRaytraceProgram->SetUniform (myGlContext,
2078     myUniformLocations[theProgramIndex][OpenGl_RT_uOriginLT], theOrigins[2]);
2079   aResult &= theRaytraceProgram->SetUniform (myGlContext,
2080     myUniformLocations[theProgramIndex][OpenGl_RT_uOriginRT], theOrigins[3]);
2081   aResult &= theRaytraceProgram->SetUniform (myGlContext,
2082     myUniformLocations[theProgramIndex][OpenGl_RT_uDirectLB], theDirects[0]);
2083   aResult &= theRaytraceProgram->SetUniform (myGlContext,
2084     myUniformLocations[theProgramIndex][OpenGl_RT_uDirectRB], theDirects[1]);
2085   aResult &= theRaytraceProgram->SetUniform (myGlContext,
2086     myUniformLocations[theProgramIndex][OpenGl_RT_uDirectLT], theDirects[2]);
2087   aResult &= theRaytraceProgram->SetUniform (myGlContext,
2088     myUniformLocations[theProgramIndex][OpenGl_RT_uDirectRT], theDirects[3]);
2089   aResult &= theRaytraceProgram->SetUniform (myGlContext,
2090     myUniformLocations[theProgramIndex][OpenGl_RT_uUnviewMat], theUnviewMat);
2091
2092   // Set window size
2093   aResult &= theRaytraceProgram->SetUniform (myGlContext,
2094     myUniformLocations[theProgramIndex][OpenGl_RT_uWinSizeX], theSizeX);
2095   aResult &= theRaytraceProgram->SetUniform (myGlContext,
2096     myUniformLocations[theProgramIndex][OpenGl_RT_uWinSizeY], theSizeY);
2097
2098   // Set scene parameters
2099   aResult &= theRaytraceProgram->SetUniform (myGlContext,
2100     myUniformLocations[theProgramIndex][OpenGl_RT_uSceneRad], myRaytraceSceneRadius);
2101   aResult &= theRaytraceProgram->SetUniform (myGlContext,
2102     myUniformLocations[theProgramIndex][OpenGl_RT_uSceneEps], myRaytraceSceneEpsilon);
2103   aResult &= theRaytraceProgram->SetUniform (myGlContext,
2104     myUniformLocations[theProgramIndex][OpenGl_RT_uLightCount], aLightSourceBufferSize);
2105   aResult &= theRaytraceProgram->SetUniform (myGlContext,
2106     myUniformLocations[theProgramIndex][OpenGl_RT_uLightAmbnt], myRaytraceGeometry.Ambient);
2107
2108   // Set rendering options
2109   aResult &= theRaytraceProgram->SetUniform (myGlContext,
2110     myUniformLocations[theProgramIndex][OpenGl_RT_uShadEnabled], theCView.RenderParams.IsShadowEnabled ? 1 : 0);
2111   aResult &= theRaytraceProgram->SetUniform (myGlContext,
2112     myUniformLocations[theProgramIndex][OpenGl_RT_uReflEnabled], theCView.RenderParams.IsReflectionEnabled ? 1 : 0);
2113
2114   // Set array of 64-bit texture handles
2115   if (myGlContext->arbTexBindless != NULL && myRaytraceGeometry.HasTextures())
2116   {
2117     aResult &= theRaytraceProgram->SetUniform (myGlContext, "uTextureSamplers",
2118       static_cast<GLsizei> (myRaytraceGeometry.TextureHandles().size()), &myRaytraceGeometry.TextureHandles()[0]);
2119   }
2120
2121   if (!aResult)
2122   {
2123 #ifdef RAY_TRACE_PRINT_INFO
2124     std::cout << "Info: Not all uniforms were detected (for program " << theProgramIndex << ")" << std::endl;
2125 #endif
2126   }
2127
2128   return aResult;
2129 }
2130
2131 // =======================================================================
2132 // function : RunRaytraceShaders
2133 // purpose  : Runs ray-tracing shader programs
2134 // =======================================================================
2135 Standard_Boolean OpenGl_Workspace::RunRaytraceShaders (const Graphic3d_CView& theCView,
2136                                                        const Standard_Integer theSizeX,
2137                                                        const Standard_Integer theSizeY,
2138                                                        const OpenGl_Vec3      theOrigins[4],
2139                                                        const OpenGl_Vec3      theDirects[4],
2140                                                        const OpenGl_Mat4&     theUnviewMat,
2141                                                        OpenGl_FrameBuffer*    theFrameBuffer)
2142 {
2143   mySceneMinPointTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneMinPointTexture);
2144   mySceneMaxPointTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneMaxPointTexture);
2145   mySceneNodeInfoTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneNodeInfoTexture);
2146   myGeometryVertexTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryVertexTexture);
2147   myGeometryNormalTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryNormalTexture);
2148   myGeometryTexCrdTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryTexCrdTexture);
2149   myGeometryTriangTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryTriangTexture);
2150   mySceneTransformTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneTransformTexture);
2151   myRaytraceMaterialTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_RaytraceMaterialTexture);
2152   myRaytraceLightSrcTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_RaytraceLightSrcTexture);
2153   
2154   myOpenGlFBO->ColorTexture()->Bind        (myGlContext, GL_TEXTURE0 + OpenGl_RT_OpenGlColorTexture);
2155   myOpenGlFBO->DepthStencilTexture()->Bind (myGlContext, GL_TEXTURE0 + OpenGl_RT_OpenGlDepthTexture);
2156
2157   if (theCView.RenderParams.IsAntialiasingEnabled) // render source image to FBO
2158   {
2159     myRaytraceFBO1->BindBuffer (myGlContext);
2160     
2161     glDisable (GL_BLEND);
2162   }
2163
2164   myGlContext->BindProgram (myRaytraceProgram);
2165
2166   SetUniformState (theCView,
2167                    theSizeX,
2168                    theSizeY,
2169                    theOrigins,
2170                    theDirects,
2171                    theUnviewMat,
2172                    0, // ID of RT program
2173                    myRaytraceProgram);
2174
2175   myGlContext->core20fwd->glEnableVertexAttribArray (Graphic3d_TOA_POS);
2176   {
2177     myGlContext->core20fwd->glVertexAttribPointer (Graphic3d_TOA_POS, 3, GL_FLOAT, GL_FALSE, 0, NULL);
2178     myGlContext->core15fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
2179   }
2180   myGlContext->core20fwd->glDisableVertexAttribArray (Graphic3d_TOA_POS);
2181
2182   if (!theCView.RenderParams.IsAntialiasingEnabled)
2183   {
2184     myGlContext->BindProgram (NULL);
2185
2186     myOpenGlFBO->ColorTexture()->Unbind        (myGlContext, GL_TEXTURE0 + OpenGl_RT_OpenGlColorTexture);
2187     myOpenGlFBO->DepthStencilTexture()->Unbind (myGlContext, GL_TEXTURE0 + OpenGl_RT_OpenGlDepthTexture);
2188     mySceneMinPointTexture->UnbindTexture     (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneMinPointTexture);
2189     mySceneMaxPointTexture->UnbindTexture     (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneMaxPointTexture);
2190     mySceneNodeInfoTexture->UnbindTexture     (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneNodeInfoTexture);
2191     myGeometryVertexTexture->UnbindTexture     (myGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryVertexTexture);
2192     myGeometryNormalTexture->UnbindTexture     (myGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryNormalTexture);
2193     myGeometryTexCrdTexture->UnbindTexture     (myGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryTexCrdTexture);
2194     myGeometryTriangTexture->UnbindTexture     (myGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryTriangTexture);
2195     mySceneTransformTexture->UnbindTexture     (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneTransformTexture);
2196     myRaytraceMaterialTexture->UnbindTexture   (myGlContext, GL_TEXTURE0 + OpenGl_RT_RaytraceMaterialTexture);
2197     myRaytraceLightSrcTexture->UnbindTexture   (myGlContext, GL_TEXTURE0 + OpenGl_RT_RaytraceLightSrcTexture);
2198
2199     myGlContext->core15fwd->glActiveTexture (GL_TEXTURE0);
2200
2201     return Standard_True;
2202   }
2203
2204   myRaytraceFBO1->ColorTexture()->Bind (myGlContext, GL_TEXTURE0 + OpenGl_RT_FSAAInputTexture);
2205
2206   myGlContext->BindProgram (myPostFSAAProgram);
2207
2208   SetUniformState (theCView,
2209                    theSizeX,
2210                    theSizeY,
2211                    theOrigins,
2212                    theDirects,
2213                    theUnviewMat,
2214                    1, // ID of FSAA program
2215                    myPostFSAAProgram);
2216
2217   myGlContext->core20fwd->glEnableVertexAttribArray (Graphic3d_TOA_POS);
2218   myGlContext->core20fwd->glVertexAttribPointer (Graphic3d_TOA_POS, 3, GL_FLOAT, GL_FALSE, 0, NULL);
2219
2220   // Perform multi-pass adaptive FSAA using ping-pong technique.
2221   // We use 'FLIPTRI' sampling pattern changing for every pixel
2222   // (3 additional samples per pixel, the 1st sample is already
2223   // available from initial ray-traced image).
2224   for (Standard_Integer anIt = 1; anIt < 4; ++anIt)
2225   {
2226     GLfloat aOffsetX = 1.f / theSizeX;
2227     GLfloat aOffsetY = 1.f / theSizeY;
2228
2229     if (anIt == 1)
2230     {
2231       aOffsetX *= -0.55f;
2232       aOffsetY *=  0.55f;
2233     }
2234     else if (anIt == 2)
2235     {
2236       aOffsetX *=  0.00f;
2237       aOffsetY *= -0.55f;
2238     }
2239     else if (anIt == 3)
2240     {
2241       aOffsetX *= 0.55f;
2242       aOffsetY *= 0.00f;
2243     }
2244
2245     myPostFSAAProgram->SetUniform (myGlContext,
2246       myUniformLocations[1][OpenGl_RT_uSamples], anIt + 1);
2247     myPostFSAAProgram->SetUniform (myGlContext,
2248       myUniformLocations[1][OpenGl_RT_uOffsetX], aOffsetX);
2249     myPostFSAAProgram->SetUniform (myGlContext,
2250       myUniformLocations[1][OpenGl_RT_uOffsetY], aOffsetY);
2251
2252     Handle(OpenGl_FrameBuffer)& aFramebuffer = anIt % 2 ? myRaytraceFBO2 : myRaytraceFBO1;
2253
2254     if (anIt == 3) // disable FBO on last iteration
2255     {
2256       glEnable (GL_BLEND);
2257
2258       if (theFrameBuffer != NULL)
2259         theFrameBuffer->BindBuffer (myGlContext);
2260     }
2261     else
2262     {
2263       aFramebuffer->BindBuffer (myGlContext);
2264     }
2265
2266     myGlContext->core15fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
2267
2268     if (anIt != 3) // set input for the next pass
2269     {
2270       aFramebuffer->ColorTexture()->Bind (myGlContext, GL_TEXTURE0 + OpenGl_RT_FSAAInputTexture);
2271       aFramebuffer->UnbindBuffer (myGlContext);
2272     }
2273   }
2274
2275   myGlContext->core20fwd->glDisableVertexAttribArray (Graphic3d_TOA_POS);
2276
2277   myGlContext->BindProgram (NULL);
2278   myRaytraceFBO1->ColorTexture()->Unbind     (myGlContext, GL_TEXTURE0 + OpenGl_RT_FSAAInputTexture);
2279   myOpenGlFBO->ColorTexture()->Unbind        (myGlContext, GL_TEXTURE0 + OpenGl_RT_OpenGlColorTexture);
2280   myOpenGlFBO->DepthStencilTexture()->Unbind (myGlContext, GL_TEXTURE0 + OpenGl_RT_OpenGlDepthTexture);
2281   mySceneMinPointTexture->UnbindTexture     (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneMinPointTexture);
2282   mySceneMaxPointTexture->UnbindTexture     (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneMaxPointTexture);
2283   mySceneNodeInfoTexture->UnbindTexture     (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneNodeInfoTexture);
2284   myGeometryVertexTexture->UnbindTexture     (myGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryVertexTexture);
2285   myGeometryNormalTexture->UnbindTexture     (myGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryNormalTexture);
2286   myGeometryTexCrdTexture->UnbindTexture     (myGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryTexCrdTexture);
2287   myGeometryTriangTexture->UnbindTexture     (myGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryTriangTexture);
2288   mySceneTransformTexture->UnbindTexture     (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneTransformTexture);
2289   myRaytraceMaterialTexture->UnbindTexture   (myGlContext, GL_TEXTURE0 + OpenGl_RT_RaytraceMaterialTexture);
2290   myRaytraceLightSrcTexture->UnbindTexture   (myGlContext, GL_TEXTURE0 + OpenGl_RT_RaytraceLightSrcTexture);
2291
2292   myGlContext->core15fwd->glActiveTexture (GL_TEXTURE0);
2293
2294   return Standard_True;
2295 }
2296
2297 // =======================================================================
2298 // function : Raytrace
2299 // purpose  : Redraws the window using OpenGL/GLSL ray-tracing
2300 // =======================================================================
2301 Standard_Boolean OpenGl_Workspace::Raytrace (const Graphic3d_CView& theCView,
2302                                              const Standard_Integer theSizeX,
2303                                              const Standard_Integer theSizeY,
2304                                              const Standard_Boolean theToSwap,
2305                                              const Aspect_CLayer2d& theCOverLayer,
2306                                              const Aspect_CLayer2d& theCUnderLayer,
2307                                              OpenGl_FrameBuffer*    theFrameBuffer)
2308 {
2309   if (!InitRaytraceResources (theCView))
2310     return Standard_False;
2311
2312   if (!ResizeRaytraceBuffers (theSizeX, theSizeY))
2313     return Standard_False;
2314
2315   if (!UpdateRaytraceEnvironmentMap())
2316     return Standard_False;
2317
2318   // Get model-view and projection matrices
2319   OpenGl_Mat4 aOrientationMatrix;
2320   OpenGl_Mat4 aViewMappingMatrix;
2321
2322   myView->GetMatrices (aOrientationMatrix,
2323                        aViewMappingMatrix);
2324
2325   OpenGl_Mat4 aInvOrientationMatrix;
2326   aOrientationMatrix.Inverted (aInvOrientationMatrix);
2327
2328   if (!UpdateRaytraceLightSources (aInvOrientationMatrix))
2329     return Standard_False;
2330
2331   OpenGl_Vec3 aOrigins[4];
2332   OpenGl_Vec3 aDirects[4];
2333   OpenGl_Mat4 anUnviewMat;
2334
2335   UpdateCamera (aOrientationMatrix,
2336                 aViewMappingMatrix,
2337                 aOrigins,
2338                 aDirects,
2339                 anUnviewMat);
2340
2341   Standard_Boolean wasBlendingEnabled = glIsEnabled (GL_BLEND);
2342   Standard_Boolean wasDepthTestEnabled = glIsEnabled (GL_DEPTH_TEST);
2343
2344   glDisable (GL_DEPTH_TEST);
2345
2346   if (theFrameBuffer != NULL)
2347   {
2348     theFrameBuffer->BindBuffer (myGlContext);
2349   }
2350
2351   if (NamedStatus & OPENGL_NS_WHITEBACK)
2352   {
2353     glClearColor (1.0f, 1.0f, 1.0f, 1.0f);
2354   }
2355   else
2356   {
2357     glClearColor (myBgColor.rgb[0],
2358                   myBgColor.rgb[1],
2359                   myBgColor.rgb[2],
2360                   1.0f);
2361   }
2362
2363   glClear (GL_COLOR_BUFFER_BIT);
2364
2365   myView->DrawBackground (*this);
2366
2367   myView->RedrawLayer2d (myPrintContext, this, theCView, theCUnderLayer);
2368
2369   myGlContext->WorldViewState.Push();
2370   myGlContext->ProjectionState.Push();
2371
2372   myGlContext->WorldViewState.SetIdentity();
2373   myGlContext->ProjectionState.SetIdentity();
2374
2375   myGlContext->ApplyProjectionMatrix();
2376   myGlContext->ApplyWorldViewMatrix();
2377
2378   glEnable (GL_BLEND);
2379   glBlendFunc (GL_ONE, GL_SRC_ALPHA);
2380
2381   // Generate ray-traced image
2382   if (myIsRaytraceDataValid)
2383   {
2384     myRaytraceScreenQuad.Bind (myGlContext);
2385
2386     if (!myRaytraceGeometry.AcquireTextures (myGlContext))
2387     {
2388       const TCollection_ExtendedString aMessage = "Error: Failed to acquire OpenGL image textures";
2389
2390       myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
2391         GL_DEBUG_TYPE_ERROR_ARB, 0, GL_DEBUG_SEVERITY_MEDIUM_ARB, aMessage);
2392     }
2393
2394     RunRaytraceShaders (theCView,
2395                         theSizeX,
2396                         theSizeY,
2397                         aOrigins,
2398                         aDirects,
2399                         anUnviewMat,
2400                         theFrameBuffer);
2401
2402     if (!myRaytraceGeometry.ReleaseTextures (myGlContext))
2403     {
2404       const TCollection_ExtendedString aMessage = "Error: Failed to release OpenGL image textures";
2405
2406       myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
2407         GL_DEBUG_TYPE_ERROR_ARB, 0, GL_DEBUG_SEVERITY_MEDIUM_ARB, aMessage);
2408     }
2409
2410     myRaytraceScreenQuad.Unbind (myGlContext);
2411   }
2412
2413   if (!wasBlendingEnabled)
2414     glDisable (GL_BLEND);
2415
2416   if (wasDepthTestEnabled)
2417     glEnable (GL_DEPTH_TEST);
2418
2419   myGlContext->WorldViewState.Pop();
2420   myGlContext->ProjectionState.Pop();
2421
2422   myGlContext->ApplyProjectionMatrix();
2423
2424   // Redraw trihedron
2425   myView->RedrawTrihedron (this);
2426
2427   // Redraw overlay
2428   const int aMode = 0;
2429   DisplayCallback (theCView, (aMode | OCC_PRE_OVERLAY));
2430   myView->RedrawLayer2d (myPrintContext, this, theCView, theCOverLayer);
2431   DisplayCallback (theCView, aMode);
2432
2433   // Swap the buffers
2434   if (theToSwap)
2435   {
2436     GetGlContext()->SwapBuffers();
2437     myBackBufferRestored = Standard_False;
2438   }
2439   else
2440   {
2441     glFlush();
2442   }
2443
2444   return Standard_True;
2445 }
2446
2447 IMPLEMENT_STANDARD_HANDLE(OpenGl_RaytraceFilter, OpenGl_RenderFilter)
2448 IMPLEMENT_STANDARD_RTTIEXT(OpenGl_RaytraceFilter, OpenGl_RenderFilter)
2449
2450 // =======================================================================
2451 // function : CanRender
2452 // purpose  :
2453 // =======================================================================
2454 Standard_Boolean OpenGl_RaytraceFilter::CanRender (const OpenGl_Element* theElement)
2455 {
2456   Standard_Boolean aPrevFilterResult = Standard_True;
2457   if (!myPrevRenderFilter.IsNull())
2458   {
2459     aPrevFilterResult = myPrevRenderFilter->CanRender(theElement);
2460   }
2461   return aPrevFilterResult &&
2462          !OpenGl_Raytrace::IsRaytracedElement (theElement);
2463 }