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