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