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