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