1 // Created on: 2013-08-27
2 // Created by: Denis BOGOLEPOV
3 // Copyright (c) 2013 OPEN CASCADE SAS
5 // This file is part of Open CASCADE Technology software library.
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.
13 // Alternatively, this file may be used under the terms of Open CASCADE
14 // commercial license or contractual agreement.
16 #include <OpenGl_Workspace.hxx>
18 #include <Graphic3d_TextureParams.hxx>
19 #include <OpenGl_FrameBuffer.hxx>
20 #include <OpenGl_PrimitiveArray.hxx>
21 #include <OpenGl_VertexBuffer.hxx>
22 #include <OpenGl_View.hxx>
23 #include <OSD_File.hxx>
24 #include <OSD_Protection.hxx>
26 using namespace OpenGl_Raytrace;
28 //! Use this macro to output ray-tracing debug info
29 // #define RAY_TRACE_PRINT_INFO
31 #ifdef RAY_TRACE_PRINT_INFO
32 #include <OSD_Timer.hxx>
35 // =======================================================================
36 // function : UpdateRaytraceGeometry
37 // purpose : Updates 3D scene geometry for ray tracing
38 // =======================================================================
39 Standard_Boolean OpenGl_Workspace::UpdateRaytraceGeometry (GeomUpdateMode theMode)
42 return Standard_False;
44 // Note: In 'check' mode (OpenGl_GUM_CHECK) the scene geometry is analyzed for modifications
45 // This is light-weight procedure performed for each frame
47 if (theMode == OpenGl_GUM_CHECK)
49 if (myLayersModificationStatus != myView->LayerList().ModificationState())
51 return UpdateRaytraceGeometry (OpenGl_GUM_PREPARE);
54 else if (theMode == OpenGl_GUM_PREPARE)
56 myRaytraceGeometry.ClearMaterials();
57 myArrayToTrianglesMap.clear();
59 myIsRaytraceDataValid = Standard_False;
62 // The set of processed structures (reflected to ray-tracing)
63 // This set is used to remove out-of-date records from the
64 // hash map of structures
65 std::set<const OpenGl_Structure*> anElements;
67 // Set of all currently visible and "raytracable" primitive arrays.
68 std::set<Standard_Size> anArrayIDs;
70 const OpenGl_LayerList& aList = myView->LayerList();
72 for (OpenGl_SequenceOfLayers::Iterator anLayerIt (aList.Layers()); anLayerIt.More(); anLayerIt.Next())
74 const OpenGl_Layer& aLayer = anLayerIt.Value();
75 if (aLayer.NbStructures() == 0)
78 const OpenGl_ArrayOfStructure& aStructArray = aLayer.ArrayOfStructures();
79 for (Standard_Integer anIndex = 0; anIndex < aStructArray.Length(); ++anIndex)
81 for (OpenGl_SequenceOfStructure::Iterator aStructIt (aStructArray (anIndex)); aStructIt.More(); aStructIt.Next())
83 const OpenGl_Structure* aStructure = aStructIt.Value();
85 if (theMode == OpenGl_GUM_CHECK)
87 if (CheckRaytraceStructure (aStructure))
89 return UpdateRaytraceGeometry (OpenGl_GUM_PREPARE);
92 else if (theMode == OpenGl_GUM_PREPARE)
94 if (!aStructure->IsRaytracable()
95 || !aStructure->IsVisible())
99 else if (!aStructure->ViewAffinity.IsNull()
100 && !aStructure->ViewAffinity->IsVisible (myViewId))
105 for (OpenGl_Structure::GroupIterator aGroupIter (aStructure->DrawGroups()); aGroupIter.More(); aGroupIter.Next())
107 // OpenGL elements from group (extract primitives arrays)
108 for (const OpenGl_ElementNode* aNode = aGroupIter.Value()->FirstNode(); aNode != NULL; aNode = aNode->next)
110 OpenGl_PrimitiveArray* aPrimArray = dynamic_cast<OpenGl_PrimitiveArray*> (aNode->elem);
112 if (aPrimArray != NULL)
114 // Collect all primitive arrays in scene.
115 anArrayIDs.insert (aPrimArray->GetUID());
120 else if (theMode == OpenGl_GUM_UPDATE)
122 if (!aStructure->IsRaytracable())
125 AddRaytraceStructure (aStructure, anElements);
131 if (theMode == OpenGl_GUM_PREPARE)
133 BVH_ObjectSet<Standard_ShortReal, 3>::BVH_ObjectList anUnchangedObjects;
135 // Leave only unchanged objects in myRaytraceGeometry so only their transforms and materials will be updated
136 // Objects which not in myArrayToTrianglesMap will be built from scratch.
137 for (Standard_Integer anObjectIdx = 0; anObjectIdx < myRaytraceGeometry.Objects().Size(); ++anObjectIdx)
139 OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
140 myRaytraceGeometry.Objects().ChangeValue (anObjectIdx).operator->());
142 // If primitive array of object not in "anArrays" set then it was hided or deleted.
143 // If primitive array present in "anArrays" set but we don't have associated object yet, then
144 // the object is new and still has to be built.
145 if ((aTriangleSet != NULL) && ((anArrayIDs.find (aTriangleSet->AssociatedPArrayID())) != anArrayIDs.end()))
147 anUnchangedObjects.Append (myRaytraceGeometry.Objects().Value (anObjectIdx));
149 myArrayToTrianglesMap[aTriangleSet->AssociatedPArrayID()] = aTriangleSet;
153 myRaytraceGeometry.Objects() = anUnchangedObjects;
155 return UpdateRaytraceGeometry (OpenGl_GUM_UPDATE);
158 if (theMode == OpenGl_GUM_UPDATE)
160 // Actualize the hash map of structures -- remove out-of-date records
161 std::map<const OpenGl_Structure*, Standard_Size>::iterator anIter = myStructureStates.begin();
163 while (anIter != myStructureStates.end())
165 if (anElements.find (anIter->first) == anElements.end())
167 myStructureStates.erase (anIter++);
175 // Actualize OpenGL layer list state
176 myLayersModificationStatus = myView->LayerList().ModificationState();
178 // Rebuild bottom-level and high-level BVHs
179 myRaytraceGeometry.ProcessAcceleration();
181 const Standard_ShortReal aMinRadius = Max (fabs (myRaytraceGeometry.Box().CornerMin().x()), Max (
182 fabs (myRaytraceGeometry.Box().CornerMin().y()), fabs (myRaytraceGeometry.Box().CornerMin().z())));
183 const Standard_ShortReal aMaxRadius = Max (fabs (myRaytraceGeometry.Box().CornerMax().x()), Max (
184 fabs (myRaytraceGeometry.Box().CornerMax().y()), fabs (myRaytraceGeometry.Box().CornerMax().z())));
186 myRaytraceSceneRadius = 2.f /* scale factor */ * Max (aMinRadius, aMaxRadius);
188 const BVH_Vec3f aSize = myRaytraceGeometry.Box().Size();
190 myRaytraceSceneEpsilon = Max (1e-6f, 1e-4f * sqrtf (
191 aSize.x() * aSize.x() + aSize.y() * aSize.y() + aSize.z() * aSize.z()));
193 return UploadRaytraceData();
196 return Standard_True;
199 // =======================================================================
200 // function : CheckRaytraceStructure
201 // purpose : Checks to see if the structure is modified
202 // =======================================================================
203 Standard_Boolean OpenGl_Workspace::CheckRaytraceStructure (const OpenGl_Structure* theStructure)
205 if (!theStructure->IsRaytracable())
207 // Checks to see if all ray-tracable elements were
208 // removed from the structure
209 if (theStructure->ModificationState() > 0)
211 theStructure->ResetModificationState();
212 return Standard_True;
215 return Standard_False;
218 std::map<const OpenGl_Structure*, Standard_Size>::iterator aStructState = myStructureStates.find (theStructure);
220 if (aStructState != myStructureStates.end())
221 return aStructState->second != theStructure->ModificationState();
223 return Standard_True;
226 // =======================================================================
227 // function : BuildTexTransform
228 // purpose : Constructs texture transformation matrix
229 // =======================================================================
230 void BuildTexTransform (const Handle(Graphic3d_TextureParams)& theParams, BVH_Mat4f& theMatrix)
232 theMatrix.InitIdentity();
235 const Graphic3d_Vec2& aScale = theParams->Scale();
237 theMatrix.ChangeValue (0, 0) *= aScale.x();
238 theMatrix.ChangeValue (1, 0) *= aScale.x();
239 theMatrix.ChangeValue (2, 0) *= aScale.x();
240 theMatrix.ChangeValue (3, 0) *= aScale.x();
242 theMatrix.ChangeValue (0, 1) *= aScale.y();
243 theMatrix.ChangeValue (1, 1) *= aScale.y();
244 theMatrix.ChangeValue (2, 1) *= aScale.y();
245 theMatrix.ChangeValue (3, 1) *= aScale.y();
248 const Graphic3d_Vec2 aTrans = -theParams->Translation();
250 theMatrix.ChangeValue (0, 3) = theMatrix.GetValue (0, 0) * aTrans.x() +
251 theMatrix.GetValue (0, 1) * aTrans.y();
253 theMatrix.ChangeValue (1, 3) = theMatrix.GetValue (1, 0) * aTrans.x() +
254 theMatrix.GetValue (1, 1) * aTrans.y();
256 theMatrix.ChangeValue (2, 3) = theMatrix.GetValue (2, 0) * aTrans.x() +
257 theMatrix.GetValue (2, 1) * aTrans.y();
260 const Standard_ShortReal aSin = std::sin (
261 -theParams->Rotation() * static_cast<Standard_ShortReal> (M_PI / 180.0));
262 const Standard_ShortReal aCos = std::cos (
263 -theParams->Rotation() * static_cast<Standard_ShortReal> (M_PI / 180.0));
265 BVH_Mat4f aRotationMat;
266 aRotationMat.SetValue (0, 0, aCos);
267 aRotationMat.SetValue (1, 1, aCos);
268 aRotationMat.SetValue (0, 1, -aSin);
269 aRotationMat.SetValue (1, 0, aSin);
271 theMatrix = theMatrix * aRotationMat;
274 // =======================================================================
275 // function : CreateMaterial
276 // purpose : Creates ray-tracing material properties
277 // =======================================================================
278 Standard_Boolean OpenGl_Workspace::CreateMaterial (const OpenGl_AspectFace* theAspect, OpenGl_RaytraceMaterial& theMaterial)
280 const OPENGL_SURF_PROP& aProperties = theAspect->IntFront();
282 const Standard_ShortReal* aSrcAmbient =
283 aProperties.isphysic ? aProperties.ambcol.rgb : aProperties.matcol.rgb;
285 theMaterial.Ambient = BVH_Vec4f (aSrcAmbient[0] * aProperties.amb,
286 aSrcAmbient[1] * aProperties.amb,
287 aSrcAmbient[2] * aProperties.amb,
290 const Standard_ShortReal* aSrcDiffuse =
291 aProperties.isphysic ? aProperties.difcol.rgb : aProperties.matcol.rgb;
293 theMaterial.Diffuse = BVH_Vec4f (aSrcDiffuse[0] * aProperties.diff,
294 aSrcDiffuse[1] * aProperties.diff,
295 aSrcDiffuse[2] * aProperties.diff,
296 -1.f /* no texture */);
298 theMaterial.Specular = BVH_Vec4f (
299 (aProperties.isphysic ? aProperties.speccol.rgb[0] : 1.f) * aProperties.spec,
300 (aProperties.isphysic ? aProperties.speccol.rgb[1] : 1.f) * aProperties.spec,
301 (aProperties.isphysic ? aProperties.speccol.rgb[2] : 1.f) * aProperties.spec,
304 const Standard_ShortReal* aSrcEmission =
305 aProperties.isphysic ? aProperties.emscol.rgb : aProperties.matcol.rgb;
307 theMaterial.Emission = BVH_Vec4f (aSrcEmission[0] * aProperties.emsv,
308 aSrcEmission[1] * aProperties.emsv,
309 aSrcEmission[2] * aProperties.emsv,
312 // Note: Here we use sub-linear transparency function
313 // to produce realistic-looking transparency effect
314 theMaterial.Transparency = BVH_Vec4f (powf (aProperties.trans, 0.75f),
315 1.f - aProperties.trans,
316 aProperties.index == 0 ? 1.f : aProperties.index,
317 aProperties.index == 0 ? 1.f : 1.f / aProperties.index);
319 const Standard_ShortReal aMaxRefl = Max (theMaterial.Diffuse.x() + theMaterial.Specular.x(),
320 Max (theMaterial.Diffuse.y() + theMaterial.Specular.y(),
321 theMaterial.Diffuse.z() + theMaterial.Specular.z()));
323 const Standard_ShortReal aReflectionScale = 0.75f / aMaxRefl;
325 theMaterial.Reflection = BVH_Vec4f (
326 aProperties.speccol.rgb[0] * aProperties.spec * aReflectionScale,
327 aProperties.speccol.rgb[1] * aProperties.spec * aReflectionScale,
328 aProperties.speccol.rgb[2] * aProperties.spec * aReflectionScale,
331 if (theAspect->DoTextureMap())
333 if (myGlContext->arbTexBindless != NULL)
335 BuildTexTransform (theAspect->TextureParams(), theMaterial.TextureTransform);
336 theMaterial.Diffuse.w() = static_cast<Standard_ShortReal> (
337 myRaytraceGeometry.AddTexture (theAspect->TextureRes (myGlContext)));
339 else if (!myIsRaytraceWarnTextures)
341 myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
342 GL_DEBUG_TYPE_PORTABILITY_ARB, 0, GL_DEBUG_SEVERITY_HIGH_ARB,
343 "Warning: texturing in Ray-Trace requires GL_ARB_bindless_texture extension which is missing. "
344 "Textures will be ignored.");
345 myIsRaytraceWarnTextures = Standard_True;
349 return Standard_True;
352 // =======================================================================
353 // function : AddRaytraceStructure
354 // purpose : Adds OpenGL structure to ray-traced scene geometry
355 // =======================================================================
356 Standard_Boolean OpenGl_Workspace::AddRaytraceStructure (const OpenGl_Structure* theStructure, std::set<const OpenGl_Structure*>& theElements)
358 theElements.insert (theStructure);
360 if (!theStructure->IsVisible())
362 myStructureStates[theStructure] = theStructure->ModificationState();
363 return Standard_True;
366 // Get structure material
367 Standard_Integer aStructMatID = -1;
369 if (theStructure->AspectFace() != NULL)
371 aStructMatID = static_cast<Standard_Integer> (myRaytraceGeometry.Materials.size());
373 OpenGl_RaytraceMaterial aStructMaterial;
374 CreateMaterial (theStructure->AspectFace(), aStructMaterial);
376 myRaytraceGeometry.Materials.push_back (aStructMaterial);
379 Standard_ShortReal aStructTransformArr[16];
380 Standard_ShortReal* aStructTransform = NULL;
381 if (theStructure->Transformation()->mat != NULL)
383 aStructTransform = aStructTransformArr;
384 for (Standard_Integer i = 0; i < 4; ++i)
386 for (Standard_Integer j = 0; j < 4; ++j)
388 aStructTransform[j * 4 + i] = theStructure->Transformation()->mat[i][j];
393 AddRaytraceGroups (theStructure, aStructMatID, aStructTransform);
395 // Process all connected OpenGL structures
396 for (OpenGl_ListOfStructure::Iterator anIts (theStructure->ConnectedStructures()); anIts.More(); anIts.Next())
398 if (anIts.Value()->IsRaytracable())
399 AddRaytraceGroups (anIts.Value(), aStructMatID, aStructTransform);
402 myStructureStates[theStructure] = theStructure->ModificationState();
403 return Standard_True;
406 // =======================================================================
407 // function : AddRaytraceGroups
408 // purpose : Adds OpenGL groups to ray-traced scene geometry
409 // =======================================================================
410 Standard_Boolean OpenGl_Workspace::AddRaytraceGroups (const OpenGl_Structure* theStructure,
411 const Standard_Integer theStructMatId,
412 const Standard_ShortReal* theTransform)
414 for (OpenGl_Structure::GroupIterator aGroupIter (theStructure->DrawGroups()); aGroupIter.More(); aGroupIter.Next())
416 // Get group material
417 Standard_Integer aGroupMatID = -1;
418 if (aGroupIter.Value()->AspectFace() != NULL)
420 aGroupMatID = static_cast<Standard_Integer> (myRaytraceGeometry.Materials.size());
422 OpenGl_RaytraceMaterial aGroupMaterial;
423 CreateMaterial (aGroupIter.Value()->AspectFace(), aGroupMaterial);
425 myRaytraceGeometry.Materials.push_back (aGroupMaterial);
428 Standard_Integer aMatID = aGroupMatID < 0 ? theStructMatId : aGroupMatID;
432 aMatID = static_cast<Standard_Integer> (myRaytraceGeometry.Materials.size());
434 myRaytraceGeometry.Materials.push_back (OpenGl_RaytraceMaterial());
437 // Add OpenGL elements from group (extract primitives arrays and aspects)
438 for (const OpenGl_ElementNode* aNode = aGroupIter.Value()->FirstNode(); aNode != NULL; aNode = aNode->next)
440 OpenGl_AspectFace* anAspect = dynamic_cast<OpenGl_AspectFace*> (aNode->elem);
441 if (anAspect != NULL)
443 aMatID = static_cast<Standard_Integer> (myRaytraceGeometry.Materials.size());
445 OpenGl_RaytraceMaterial aMaterial;
446 CreateMaterial (anAspect, aMaterial);
448 myRaytraceGeometry.Materials.push_back (aMaterial);
452 OpenGl_PrimitiveArray* aPrimArray = dynamic_cast<OpenGl_PrimitiveArray*> (aNode->elem);
454 if (aPrimArray != NULL)
456 std::map<Standard_Size, OpenGl_TriangleSet*>::iterator aSetIter = myArrayToTrianglesMap.find (aPrimArray->GetUID());
458 if (aSetIter != myArrayToTrianglesMap.end())
460 OpenGl_TriangleSet* aSet = aSetIter->second;
462 BVH_Transform<Standard_ShortReal, 4>* aTransform = new BVH_Transform<Standard_ShortReal, 4>();
464 if (theTransform != NULL)
466 aTransform->SetTransform (*(reinterpret_cast<const BVH_Mat4f*> (theTransform)));
469 aSet->SetProperties (aTransform);
471 if (aSet->MaterialIndex() != OpenGl_TriangleSet::INVALID_MATERIAL && aSet->MaterialIndex() != aMatID)
473 aSet->SetMaterialIndex (aMatID);
478 NCollection_Handle<BVH_Object<Standard_ShortReal, 3> > aSet =
479 AddRaytracePrimitiveArray (aPrimArray, aMatID, 0);
483 BVH_Transform<Standard_ShortReal, 4>* aTransform = new BVH_Transform<Standard_ShortReal, 4>;
485 if (theTransform != NULL)
487 aTransform->SetTransform (*(reinterpret_cast<const BVH_Mat4f*> (theTransform)));
490 aSet->SetProperties (aTransform);
492 myRaytraceGeometry.Objects().Append (aSet);
500 return Standard_True;
503 // =======================================================================
504 // function : AddRaytracePrimitiveArray
505 // purpose : Adds OpenGL primitive array to ray-traced scene geometry
506 // =======================================================================
507 OpenGl_TriangleSet* OpenGl_Workspace::AddRaytracePrimitiveArray (const OpenGl_PrimitiveArray* theArray,
508 Standard_Integer theMatID,
509 const OpenGl_Mat4* theTransform)
511 const Handle(Graphic3d_IndexBuffer)& anIndices = theArray->Indices();
512 const Handle(Graphic3d_Buffer)& anAttribs = theArray->Attributes();
513 const Handle(Graphic3d_BoundBuffer)& aBounds = theArray->Bounds();
514 if (theArray->DrawMode() < GL_TRIANGLES
515 #if !defined(GL_ES_VERSION_2_0)
516 || theArray->DrawMode() > GL_POLYGON
518 || theArray->DrawMode() > GL_TRIANGLE_FAN
520 || anAttribs.IsNull())
525 #ifdef RAY_TRACE_PRINT_INFO
526 switch (theArray->DrawMode())
528 case GL_TRIANGLES: std::cout << "\tAdding GL_TRIANGLES\n"; break;
529 case GL_TRIANGLE_FAN: std::cout << "\tAdding GL_TRIANGLE_FAN\n"; break;
530 case GL_TRIANGLE_STRIP: std::cout << "\tAdding GL_TRIANGLE_STRIP\n"; break;
531 #if !defined(GL_ES_VERSION_2_0)
532 case GL_QUADS: std::cout << "\tAdding GL_QUADS\n"; break;
533 case GL_QUAD_STRIP: std::cout << "\tAdding GL_QUAD_STRIP\n"; break;
534 case GL_POLYGON: std::cout << "\tAdding GL_POLYGON\n"; break;
539 OpenGl_Mat4 aNormalMatrix;
541 if (theTransform != NULL)
543 Standard_ASSERT_RETURN (theTransform->Inverted (aNormalMatrix),
544 "Error: Failed to compute normal transformation matrix", NULL);
546 aNormalMatrix.Transpose();
549 OpenGl_TriangleSet* aSet = new OpenGl_TriangleSet (theArray->GetUID());
551 aSet->Vertices.reserve (anAttribs->NbElements);
552 aSet->Normals .reserve (anAttribs->NbElements);
553 aSet->TexCrds .reserve (anAttribs->NbElements);
555 const size_t aVertFrom = aSet->Vertices.size();
556 for (Standard_Integer anAttribIter = 0; anAttribIter < anAttribs->NbAttributes; ++anAttribIter)
558 const Graphic3d_Attribute& anAttrib = anAttribs->Attribute (anAttribIter);
559 const size_t anOffset = anAttribs->AttributeOffset (anAttribIter);
560 if (anAttrib.Id == Graphic3d_TOA_POS)
562 if (anAttrib.DataType == Graphic3d_TOD_VEC3
563 || anAttrib.DataType == Graphic3d_TOD_VEC4)
565 for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
567 aSet->Vertices.push_back (
568 *reinterpret_cast<const Graphic3d_Vec3* >(anAttribs->value (aVertIter) + anOffset));
571 else if (anAttrib.DataType == Graphic3d_TOD_VEC2)
573 for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
575 const Graphic3d_Vec2& aVert = *reinterpret_cast<const Graphic3d_Vec2* >(anAttribs->value (aVertIter) + anOffset);
576 aSet->Vertices.push_back (BVH_Vec3f (aVert.x(), aVert.y(), 0.0f));
580 else if (anAttrib.Id == Graphic3d_TOA_NORM)
582 if (anAttrib.DataType == Graphic3d_TOD_VEC3
583 || anAttrib.DataType == Graphic3d_TOD_VEC4)
585 for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
587 aSet->Normals.push_back (
588 *reinterpret_cast<const Graphic3d_Vec3* >(anAttribs->value (aVertIter) + anOffset));
592 else if (anAttrib.Id == Graphic3d_TOA_UV)
594 if (anAttrib.DataType == Graphic3d_TOD_VEC2)
596 for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
598 aSet->TexCrds.push_back (
599 *reinterpret_cast<const Graphic3d_Vec2* >(anAttribs->value (aVertIter) + anOffset));
605 if (aSet->Normals.size() != aSet->Vertices.size())
607 for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
609 aSet->Normals.push_back (BVH_Vec3f());
613 if (aSet->TexCrds.size() != aSet->Vertices.size())
615 for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
617 aSet->TexCrds.push_back (BVH_Vec2f());
621 if (theTransform != NULL)
623 for (size_t aVertIter = aVertFrom; aVertIter < aSet->Vertices.size(); ++aVertIter)
625 BVH_Vec3f& aVertex = aSet->Vertices[aVertIter];
627 BVH_Vec4f aTransVertex =
628 *theTransform * BVH_Vec4f (aVertex.x(), aVertex.y(), aVertex.z(), 1.f);
630 aVertex = BVH_Vec3f (aTransVertex.x(), aTransVertex.y(), aTransVertex.z());
632 for (size_t aVertIter = aVertFrom; aVertIter < aSet->Normals.size(); ++aVertIter)
634 BVH_Vec3f& aNormal = aSet->Normals[aVertIter];
636 BVH_Vec4f aTransNormal =
637 aNormalMatrix * BVH_Vec4f (aNormal.x(), aNormal.y(), aNormal.z(), 0.f);
639 aNormal = BVH_Vec3f (aTransNormal.x(), aTransNormal.y(), aTransNormal.z());
643 if (!aBounds.IsNull())
645 #ifdef RAY_TRACE_PRINT_INFO
646 std::cout << "\tNumber of bounds = " << aBounds->NbBounds << std::endl;
649 Standard_Integer aBoundStart = 0;
650 for (Standard_Integer aBound = 0; aBound < aBounds->NbBounds; ++aBound)
652 const Standard_Integer aVertNum = aBounds->Bounds[aBound];
654 #ifdef RAY_TRACE_PRINT_INFO
655 std::cout << "\tAdding indices from bound " << aBound << ": " <<
656 aBoundStart << " .. " << aVertNum << std::endl;
659 if (!AddRaytraceVertexIndices (*aSet, *theArray, aBoundStart, aVertNum, theMatID))
665 aBoundStart += aVertNum;
670 const Standard_Integer aVertNum = !anIndices.IsNull() ? anIndices->NbElements : anAttribs->NbElements;
672 #ifdef RAY_TRACE_PRINT_INFO
673 std::cout << "\tAdding indices from array: " << aVertNum << std::endl;
676 if (!AddRaytraceVertexIndices (*aSet, *theArray, 0, aVertNum, theMatID))
684 if (aSet->Size() != 0)
690 // =======================================================================
691 // function : AddRaytraceVertexIndices
692 // purpose : Adds vertex indices to ray-traced scene geometry
693 // =======================================================================
694 Standard_Boolean OpenGl_Workspace::AddRaytraceVertexIndices (OpenGl_TriangleSet& theSet,
695 const OpenGl_PrimitiveArray& theArray,
696 Standard_Integer theOffset,
697 Standard_Integer theCount,
698 Standard_Integer theMatID)
700 switch (theArray.DrawMode())
702 case GL_TRIANGLES: return AddRaytraceTriangleArray (theSet, theArray.Indices(), theOffset, theCount, theMatID);
703 case GL_TRIANGLE_FAN: return AddRaytraceTriangleFanArray (theSet, theArray.Indices(), theOffset, theCount, theMatID);
704 case GL_TRIANGLE_STRIP: return AddRaytraceTriangleStripArray (theSet, theArray.Indices(), theOffset, theCount, theMatID);
705 #if !defined(GL_ES_VERSION_2_0)
706 case GL_QUADS: return AddRaytraceQuadrangleArray (theSet, theArray.Indices(), theOffset, theCount, theMatID);
707 case GL_QUAD_STRIP: return AddRaytraceQuadrangleStripArray (theSet, theArray.Indices(), theOffset, theCount, theMatID);
708 case GL_POLYGON: return AddRaytracePolygonArray (theSet, theArray.Indices(), theOffset, theCount, theMatID);
711 return Standard_False;
714 // =======================================================================
715 // function : AddRaytraceTriangleArray
716 // purpose : Adds OpenGL triangle array to ray-traced scene geometry
717 // =======================================================================
718 Standard_Boolean OpenGl_Workspace::AddRaytraceTriangleArray (OpenGl_TriangleSet& theSet,
719 const Handle(Graphic3d_IndexBuffer)& theIndices,
720 Standard_Integer theOffset,
721 Standard_Integer theCount,
722 Standard_Integer theMatID)
725 return Standard_True;
727 theSet.Elements.reserve (theSet.Elements.size() + theCount / 3);
729 if (!theIndices.IsNull())
731 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; aVert += 3)
733 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0),
734 theIndices->Index (aVert + 1),
735 theIndices->Index (aVert + 2),
741 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; aVert += 3)
743 theSet.Elements.push_back (BVH_Vec4i (aVert + 0, aVert + 1, aVert + 2,
748 return Standard_True;
751 // =======================================================================
752 // function : AddRaytraceTriangleFanArray
753 // purpose : Adds OpenGL triangle fan array to ray-traced scene geometry
754 // =======================================================================
755 Standard_Boolean OpenGl_Workspace::AddRaytraceTriangleFanArray (OpenGl_TriangleSet& theSet,
756 const Handle(Graphic3d_IndexBuffer)& theIndices,
757 Standard_Integer theOffset,
758 Standard_Integer theCount,
759 Standard_Integer theMatID)
762 return Standard_True;
764 theSet.Elements.reserve (theSet.Elements.size() + theCount - 2);
766 if (!theIndices.IsNull())
768 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
770 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (theOffset),
771 theIndices->Index (aVert + 1),
772 theIndices->Index (aVert + 2),
778 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
780 theSet.Elements.push_back (BVH_Vec4i (theOffset,
787 return Standard_True;
790 // =======================================================================
791 // function : AddRaytraceTriangleStripArray
792 // purpose : Adds OpenGL triangle strip array to ray-traced scene geometry
793 // =======================================================================
794 Standard_Boolean OpenGl_Workspace::AddRaytraceTriangleStripArray (OpenGl_TriangleSet& theSet,
795 const Handle(Graphic3d_IndexBuffer)& theIndices,
796 Standard_Integer theOffset,
797 Standard_Integer theCount,
798 Standard_Integer theMatID)
801 return Standard_True;
803 theSet.Elements.reserve (theSet.Elements.size() + theCount - 2);
805 if (!theIndices.IsNull())
807 for (Standard_Integer aVert = theOffset, aCW = 0; aVert < theOffset + theCount - 2; ++aVert, aCW = (aCW + 1) % 2)
809 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + aCW ? 1 : 0),
810 theIndices->Index (aVert + aCW ? 0 : 1),
811 theIndices->Index (aVert + 2),
817 for (Standard_Integer aVert = theOffset, aCW = 0; aVert < theOffset + theCount - 2; ++aVert, aCW = (aCW + 1) % 2)
819 theSet.Elements.push_back (BVH_Vec4i (aVert + aCW ? 1 : 0,
826 return Standard_True;
829 // =======================================================================
830 // function : AddRaytraceQuadrangleArray
831 // purpose : Adds OpenGL quad array to ray-traced scene geometry
832 // =======================================================================
833 Standard_Boolean OpenGl_Workspace::AddRaytraceQuadrangleArray (OpenGl_TriangleSet& theSet,
834 const Handle(Graphic3d_IndexBuffer)& theIndices,
835 Standard_Integer theOffset,
836 Standard_Integer theCount,
837 Standard_Integer theMatID)
840 return Standard_True;
842 theSet.Elements.reserve (theSet.Elements.size() + theCount / 2);
844 if (!theIndices.IsNull())
846 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 4)
848 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0),
849 theIndices->Index (aVert + 1),
850 theIndices->Index (aVert + 2),
852 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0),
853 theIndices->Index (aVert + 2),
854 theIndices->Index (aVert + 3),
860 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 4)
862 theSet.Elements.push_back (BVH_Vec4i (aVert + 0, aVert + 1, aVert + 2,
864 theSet.Elements.push_back (BVH_Vec4i (aVert + 0, aVert + 2, aVert + 3,
869 return Standard_True;
872 // =======================================================================
873 // function : AddRaytraceQuadrangleStripArray
874 // purpose : Adds OpenGL quad strip array to ray-traced scene geometry
875 // =======================================================================
876 Standard_Boolean OpenGl_Workspace::AddRaytraceQuadrangleStripArray (OpenGl_TriangleSet& theSet,
877 const Handle(Graphic3d_IndexBuffer)& theIndices,
878 Standard_Integer theOffset,
879 Standard_Integer theCount,
880 Standard_Integer theMatID)
883 return Standard_True;
885 theSet.Elements.reserve (theSet.Elements.size() + 2 * theCount - 6);
887 if (!theIndices.IsNull())
889 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 2)
891 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0),
892 theIndices->Index (aVert + 1),
893 theIndices->Index (aVert + 2),
896 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 1),
897 theIndices->Index (aVert + 3),
898 theIndices->Index (aVert + 2),
904 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 2)
906 theSet.Elements.push_back (BVH_Vec4i (aVert + 0,
911 theSet.Elements.push_back (BVH_Vec4i (aVert + 1,
918 return Standard_True;
921 // =======================================================================
922 // function : AddRaytracePolygonArray
923 // purpose : Adds OpenGL polygon array to ray-traced scene geometry
924 // =======================================================================
925 Standard_Boolean OpenGl_Workspace::AddRaytracePolygonArray (OpenGl_TriangleSet& theSet,
926 const Handle(Graphic3d_IndexBuffer)& theIndices,
927 Standard_Integer theOffset,
928 Standard_Integer theCount,
929 Standard_Integer theMatID)
932 return Standard_True;
934 theSet.Elements.reserve (theSet.Elements.size() + theCount - 2);
936 if (!theIndices.IsNull())
938 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
940 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (theOffset),
941 theIndices->Index (aVert + 1),
942 theIndices->Index (aVert + 2),
948 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
950 theSet.Elements.push_back (BVH_Vec4i (theOffset,
957 return Standard_True;
960 // =======================================================================
961 // function : UpdateRaytraceLightSources
962 // purpose : Updates 3D scene light sources for ray-tracing
963 // =======================================================================
964 Standard_Boolean OpenGl_Workspace::UpdateRaytraceLightSources (const OpenGl_Mat4& theInvModelView)
966 myRaytraceGeometry.Sources.clear();
968 myRaytraceGeometry.Ambient = BVH_Vec4f (0.0f, 0.0f, 0.0f, 0.0f);
970 for (OpenGl_ListOfLight::Iterator anItl (myView->LightList()); anItl.More(); anItl.Next())
972 const OpenGl_Light& aLight = anItl.Value();
974 if (aLight.Type == Visual3d_TOLS_AMBIENT)
976 myRaytraceGeometry.Ambient += BVH_Vec4f (aLight.Color.r(),
983 BVH_Vec4f aDiffuse (aLight.Color.r(),
988 BVH_Vec4f aPosition (-aLight.Direction.x(),
989 -aLight.Direction.y(),
990 -aLight.Direction.z(),
993 if (aLight.Type != Visual3d_TOLS_DIRECTIONAL)
995 aPosition = BVH_Vec4f (aLight.Position.x(),
1001 if (aLight.IsHeadlight)
1003 aPosition = theInvModelView * aPosition;
1006 myRaytraceGeometry.Sources.push_back (OpenGl_RaytraceLight (aDiffuse, aPosition));
1009 if (myRaytraceLightSrcTexture.IsNull()) // create light source buffer
1011 myRaytraceLightSrcTexture = new OpenGl_TextureBufferArb;
1013 if (!myRaytraceLightSrcTexture->Create (myGlContext))
1015 #ifdef RAY_TRACE_PRINT_INFO
1016 std::cout << "Error: Failed to create light source buffer" << std::endl;
1018 return Standard_False;
1022 if (myRaytraceGeometry.Sources.size() != 0)
1024 const GLfloat* aDataPtr = myRaytraceGeometry.Sources.front().Packed();
1025 if (!myRaytraceLightSrcTexture->Init (myGlContext, 4, GLsizei (myRaytraceGeometry.Sources.size() * 2), aDataPtr))
1027 #ifdef RAY_TRACE_PRINT_INFO
1028 std::cout << "Error: Failed to upload light source buffer" << std::endl;
1030 return Standard_False;
1034 return Standard_True;
1037 // =======================================================================
1038 // function : UpdateRaytraceEnvironmentMap
1039 // purpose : Updates environment map for ray-tracing
1040 // =======================================================================
1041 Standard_Boolean OpenGl_Workspace::UpdateRaytraceEnvironmentMap()
1043 if (myView.IsNull())
1044 return Standard_False;
1046 if (myViewModificationStatus == myView->ModificationState())
1047 return Standard_True;
1049 for (Standard_Integer anIdx = 0; anIdx < 2; ++anIdx)
1051 const Handle(OpenGl_ShaderProgram)& aProgram =
1052 anIdx == 0 ? myRaytraceProgram : myPostFSAAProgram;
1054 if (!aProgram.IsNull())
1056 myGlContext->BindProgram (aProgram);
1058 if (!myView->TextureEnv().IsNull() && myView->SurfaceDetail() != Visual3d_TOD_NONE)
1060 myView->TextureEnv()->Bind (
1061 myGlContext, GL_TEXTURE0 + OpenGl_RT_EnvironmentMapTexture);
1063 aProgram->SetUniform (myGlContext,
1064 myUniformLocations[anIdx][OpenGl_RT_uEnvMapEnable], 1);
1068 aProgram->SetUniform (myGlContext,
1069 myUniformLocations[anIdx][OpenGl_RT_uEnvMapEnable], 0);
1074 myGlContext->BindProgram (NULL);
1075 myViewModificationStatus = myView->ModificationState();
1076 return Standard_True;
1079 // =======================================================================
1080 // function : Source
1081 // purpose : Returns shader source combined with prefix
1082 // =======================================================================
1083 TCollection_AsciiString OpenGl_Workspace::ShaderSource::Source() const
1085 static const TCollection_AsciiString aVersion = "#version 140";
1087 if (myPrefix.IsEmpty())
1089 return aVersion + "\n" + mySource;
1092 return aVersion + "\n" + myPrefix + "\n" + mySource;
1095 // =======================================================================
1097 // purpose : Loads shader source from specified files
1098 // =======================================================================
1099 void OpenGl_Workspace::ShaderSource::Load (
1100 const TCollection_AsciiString* theFileNames, const Standard_Integer theCount)
1104 for (Standard_Integer anIndex = 0; anIndex < theCount; ++anIndex)
1106 OSD_File aFile (theFileNames[anIndex]);
1108 Standard_ASSERT_RETURN (aFile.Exists(),
1109 "Error: Failed to find shader source file", /* none */);
1111 aFile.Open (OSD_ReadOnly, OSD_Protection());
1113 TCollection_AsciiString aSource;
1115 Standard_ASSERT_RETURN (aFile.IsOpen(),
1116 "Error: Failed to open shader source file", /* none */);
1118 aFile.Read (aSource, (Standard_Integer) aFile.Size());
1120 if (!aSource.IsEmpty())
1122 mySource += TCollection_AsciiString ("\n") + aSource;
1129 // =======================================================================
1130 // function : LoadShader
1131 // purpose : Creates new shader object with specified source
1132 // =======================================================================
1133 Handle(OpenGl_ShaderObject) OpenGl_Workspace::LoadShader (const ShaderSource& theSource, GLenum theType)
1135 Handle(OpenGl_ShaderObject) aShader = new OpenGl_ShaderObject (theType);
1137 if (!aShader->Create (myGlContext))
1139 const TCollection_ExtendedString aMessage = TCollection_ExtendedString ("Error: Failed to create ") +
1140 (theType == GL_VERTEX_SHADER ? "vertex" : "fragment") + " shader object";
1142 myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
1143 GL_DEBUG_TYPE_ERROR_ARB, 0, GL_DEBUG_SEVERITY_HIGH_ARB, aMessage);
1145 aShader->Release (myGlContext.operator->());
1147 return Handle(OpenGl_ShaderObject)();
1150 if (!aShader->LoadSource (myGlContext, theSource.Source()))
1152 const TCollection_ExtendedString aMessage = TCollection_ExtendedString ("Error: Failed to set ") +
1153 (theType == GL_VERTEX_SHADER ? "vertex" : "fragment") + " shader source";
1155 myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
1156 GL_DEBUG_TYPE_ERROR_ARB, 0, GL_DEBUG_SEVERITY_HIGH_ARB, aMessage);
1158 aShader->Release (myGlContext.operator->());
1160 return Handle(OpenGl_ShaderObject)();
1163 TCollection_AsciiString aBuildLog;
1165 if (!aShader->Compile (myGlContext))
1167 aShader->FetchInfoLog (myGlContext, aBuildLog);
1169 const TCollection_ExtendedString aMessage = TCollection_ExtendedString ("Error: Failed to compile ") +
1170 (theType == GL_VERTEX_SHADER ? "vertex" : "fragment") + " shader object:\n" + aBuildLog;
1172 myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
1173 GL_DEBUG_TYPE_ERROR_ARB, 0, GL_DEBUG_SEVERITY_HIGH_ARB, aMessage);
1175 aShader->Release (myGlContext.operator->());
1177 return Handle(OpenGl_ShaderObject)();
1179 else if (myGlContext->caps->glslWarnings)
1181 aShader->FetchInfoLog (myGlContext, aBuildLog);
1183 if (!aBuildLog.IsEmpty() && !aBuildLog.IsEqual ("No errors.\n"))
1185 const TCollection_ExtendedString aMessage = TCollection_ExtendedString (theType == GL_VERTEX_SHADER ?
1186 "Vertex" : "Fragment") + " shader was compiled with following warnings:\n" + aBuildLog;
1188 myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
1189 GL_DEBUG_TYPE_PORTABILITY_ARB, 0, GL_DEBUG_SEVERITY_LOW_ARB, aMessage);
1196 // =======================================================================
1197 // function : SafeFailBack
1198 // purpose : Performs safe exit when shaders initialization fails
1199 // =======================================================================
1200 Standard_Boolean OpenGl_Workspace::SafeFailBack (const TCollection_ExtendedString& theMessage)
1202 myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
1203 GL_DEBUG_TYPE_ERROR_ARB, 0, GL_DEBUG_SEVERITY_HIGH_ARB, theMessage);
1205 myComputeInitStatus = OpenGl_RT_FAIL;
1207 ReleaseRaytraceResources();
1209 return Standard_False;
1212 // =======================================================================
1213 // function : GenerateShaderPrefix
1214 // purpose : Generates shader prefix based on current ray-tracing options
1215 // =======================================================================
1216 TCollection_AsciiString OpenGl_Workspace::GenerateShaderPrefix()
1218 TCollection_AsciiString aPrefixString =
1219 TCollection_AsciiString ("#define STACK_SIZE ") + TCollection_AsciiString (myRaytraceParameters.StackSize) + "\n" +
1220 TCollection_AsciiString ("#define NB_BOUNCES ") + TCollection_AsciiString (myRaytraceParameters.NbBounces);
1222 if (myRaytraceParameters.TransparentShadows)
1224 aPrefixString += TCollection_AsciiString ("\n#define TRANSPARENT_SHADOWS");
1227 // If OpenGL driver supports bindless textures
1228 // activate texturing in ray-tracing mode
1229 if (myGlContext->arbTexBindless != NULL)
1231 aPrefixString += TCollection_AsciiString ("\n#define USE_TEXTURES") +
1232 TCollection_AsciiString ("\n#define MAX_TEX_NUMBER ") + TCollection_AsciiString (OpenGl_RaytraceGeometry::MAX_TEX_NUMBER);
1235 return aPrefixString;
1238 // =======================================================================
1239 // function : InitRaytraceResources
1240 // purpose : Initializes OpenGL/GLSL shader programs
1241 // =======================================================================
1242 Standard_Boolean OpenGl_Workspace::InitRaytraceResources (const Graphic3d_CView& theCView)
1244 if (myComputeInitStatus == OpenGl_RT_FAIL)
1246 return Standard_False;
1249 Standard_Boolean aToRebuildShaders = Standard_False;
1251 if (myComputeInitStatus == OpenGl_RT_INIT)
1253 if (!myIsRaytraceDataValid)
1254 return Standard_True;
1256 const Standard_Integer aRequiredStackSize =
1257 myRaytraceGeometry.HighLevelTreeDepth() + myRaytraceGeometry.BottomLevelTreeDepth();
1259 if (myRaytraceParameters.StackSize < aRequiredStackSize)
1261 myRaytraceParameters.StackSize = Max (aRequiredStackSize, THE_DEFAULT_STACK_SIZE);
1263 aToRebuildShaders = Standard_True;
1267 if (aRequiredStackSize < myRaytraceParameters.StackSize)
1269 if (myRaytraceParameters.StackSize > THE_DEFAULT_STACK_SIZE)
1271 myRaytraceParameters.StackSize = Max (aRequiredStackSize, THE_DEFAULT_STACK_SIZE);
1272 aToRebuildShaders = Standard_True;
1277 if (theCView.RenderParams.RaytracingDepth != myRaytraceParameters.NbBounces)
1279 myRaytraceParameters.NbBounces = theCView.RenderParams.RaytracingDepth;
1280 aToRebuildShaders = Standard_True;
1283 if (theCView.RenderParams.IsTransparentShadowEnabled != myRaytraceParameters.TransparentShadows)
1285 myRaytraceParameters.TransparentShadows = theCView.RenderParams.IsTransparentShadowEnabled;
1286 aToRebuildShaders = Standard_True;
1289 if (aToRebuildShaders)
1291 #ifdef RAY_TRACE_PRINT_INFO
1292 std::cout << "Info: Rebuild shaders with stack size: " << myRaytraceParameters.StackSize << std::endl;
1295 // Change state to force update all uniforms
1296 ++myViewModificationStatus;
1298 TCollection_AsciiString aPrefixString = GenerateShaderPrefix();
1300 #ifdef RAY_TRACE_PRINT_INFO
1301 std::cout << "GLSL prefix string:" << std::endl << aPrefixString << std::endl;
1304 myRaytraceShaderSource.SetPrefix (aPrefixString);
1305 myPostFSAAShaderSource.SetPrefix (aPrefixString);
1307 if (!myRaytraceShader->LoadSource (myGlContext, myRaytraceShaderSource.Source())
1308 || !myPostFSAAShader->LoadSource (myGlContext, myPostFSAAShaderSource.Source()))
1310 return SafeFailBack ("Failed to load source into ray-tracing fragment shaders");
1313 if (!myRaytraceShader->Compile (myGlContext)
1314 || !myPostFSAAShader->Compile (myGlContext))
1316 return SafeFailBack ("Failed to compile ray-tracing fragment shaders");
1319 myRaytraceProgram->SetAttributeName (myGlContext, Graphic3d_TOA_POS, "occVertex");
1320 myPostFSAAProgram->SetAttributeName (myGlContext, Graphic3d_TOA_POS, "occVertex");
1321 if (!myRaytraceProgram->Link (myGlContext)
1322 || !myPostFSAAProgram->Link (myGlContext))
1324 return SafeFailBack ("Failed to initialize vertex attributes for ray-tracing program");
1329 if (myComputeInitStatus == OpenGl_RT_NONE)
1331 if (!myGlContext->IsGlGreaterEqual (3, 1))
1333 return SafeFailBack ("Ray-tracing requires OpenGL 3.1 and higher");
1335 else if (!myGlContext->arbTboRGB32)
1337 return SafeFailBack ("Ray-tracing requires OpenGL 4.0+ or GL_ARB_texture_buffer_object_rgb32 extension");
1340 myRaytraceParameters.NbBounces = theCView.RenderParams.RaytracingDepth;
1342 TCollection_AsciiString aFolder = Graphic3d_ShaderProgram::ShadersFolder();
1344 if (aFolder.IsEmpty())
1346 return SafeFailBack ("Failed to locate shaders directory");
1349 if (myIsRaytraceDataValid)
1351 myRaytraceParameters.StackSize = Max (THE_DEFAULT_STACK_SIZE,
1352 myRaytraceGeometry.HighLevelTreeDepth() + myRaytraceGeometry.BottomLevelTreeDepth());
1355 TCollection_AsciiString aPrefixString = GenerateShaderPrefix();
1357 #ifdef RAY_TRACE_PRINT_INFO
1358 std::cout << "GLSL prefix string:" << std::endl << aPrefixString << std::endl;
1362 Handle(OpenGl_ShaderObject) aBasicVertShader = LoadShader (
1363 ShaderSource (aFolder + "/RaytraceBase.vs"), GL_VERTEX_SHADER);
1365 if (aBasicVertShader.IsNull())
1367 return SafeFailBack ("Failed to initialize ray-trace vertex shader");
1370 TCollection_AsciiString aFiles[] = { aFolder + "/RaytraceBase.fs",
1371 aFolder + "/RaytraceRender.fs" };
1373 myRaytraceShaderSource.Load (aFiles, 2);
1375 myRaytraceShaderSource.SetPrefix (aPrefixString);
1377 myRaytraceShader = LoadShader (myRaytraceShaderSource, GL_FRAGMENT_SHADER);
1379 if (myRaytraceShader.IsNull())
1381 aBasicVertShader->Release (myGlContext.operator->());
1383 return SafeFailBack ("Failed to initialize ray-trace fragment shader");
1386 myRaytraceProgram = new OpenGl_ShaderProgram;
1388 if (!myRaytraceProgram->Create (myGlContext))
1390 aBasicVertShader->Release (myGlContext.operator->());
1392 return SafeFailBack ("Failed to create ray-trace shader program");
1395 if (!myRaytraceProgram->AttachShader (myGlContext, aBasicVertShader)
1396 || !myRaytraceProgram->AttachShader (myGlContext, myRaytraceShader))
1398 aBasicVertShader->Release (myGlContext.operator->());
1400 return SafeFailBack ("Failed to attach ray-trace shader objects");
1403 myRaytraceProgram->SetAttributeName (myGlContext, Graphic3d_TOA_POS, "occVertex");
1405 TCollection_AsciiString aLinkLog;
1407 if (!myRaytraceProgram->Link (myGlContext))
1409 myRaytraceProgram->FetchInfoLog (myGlContext, aLinkLog);
1411 return SafeFailBack (TCollection_ExtendedString (
1412 "Failed to link ray-trace shader program:\n") + aLinkLog);
1414 else if (myGlContext->caps->glslWarnings)
1416 myRaytraceProgram->FetchInfoLog (myGlContext, aLinkLog);
1418 if (!aLinkLog.IsEmpty() && !aLinkLog.IsEqual ("No errors.\n"))
1420 const TCollection_ExtendedString aMessage = TCollection_ExtendedString (
1421 "Ray-trace shader program was linked with following warnings:\n") + aLinkLog;
1423 myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
1424 GL_DEBUG_TYPE_PORTABILITY_ARB, 0, GL_DEBUG_SEVERITY_LOW_ARB, aMessage);
1430 Handle(OpenGl_ShaderObject) aBasicVertShader = LoadShader (
1431 ShaderSource (aFolder + "/RaytraceBase.vs"), GL_VERTEX_SHADER);
1433 if (aBasicVertShader.IsNull())
1435 return SafeFailBack ("Failed to initialize FSAA vertex shader");
1438 TCollection_AsciiString aFiles[] = { aFolder + "/RaytraceBase.fs",
1439 aFolder + "/RaytraceSmooth.fs" };
1441 myPostFSAAShaderSource.Load (aFiles, 2);
1443 myPostFSAAShaderSource.SetPrefix (aPrefixString);
1445 myPostFSAAShader = LoadShader (myPostFSAAShaderSource, GL_FRAGMENT_SHADER);
1447 if (myPostFSAAShader.IsNull())
1449 aBasicVertShader->Release (myGlContext.operator->());
1451 return SafeFailBack ("Failed to initialize FSAA fragment shader");
1454 myPostFSAAProgram = new OpenGl_ShaderProgram;
1456 if (!myPostFSAAProgram->Create (myGlContext))
1458 aBasicVertShader->Release (myGlContext.operator->());
1460 return SafeFailBack ("Failed to create FSAA shader program");
1463 if (!myPostFSAAProgram->AttachShader (myGlContext, aBasicVertShader)
1464 || !myPostFSAAProgram->AttachShader (myGlContext, myPostFSAAShader))
1466 aBasicVertShader->Release (myGlContext.operator->());
1468 return SafeFailBack ("Failed to attach FSAA shader objects");
1471 myPostFSAAProgram->SetAttributeName (myGlContext, Graphic3d_TOA_POS, "occVertex");
1473 TCollection_AsciiString aLinkLog;
1475 if (!myPostFSAAProgram->Link (myGlContext))
1477 myPostFSAAProgram->FetchInfoLog (myGlContext, aLinkLog);
1479 return SafeFailBack (TCollection_ExtendedString (
1480 "Failed to link FSAA shader program:\n") + aLinkLog);
1482 else if (myGlContext->caps->glslWarnings)
1484 myPostFSAAProgram->FetchInfoLog (myGlContext, aLinkLog);
1486 if (!aLinkLog.IsEmpty() && !aLinkLog.IsEqual ("No errors.\n"))
1488 const TCollection_ExtendedString aMessage = TCollection_ExtendedString (
1489 "FSAA shader program was linked with following warnings:\n") + aLinkLog;
1491 myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
1492 GL_DEBUG_TYPE_PORTABILITY_ARB, 0, GL_DEBUG_SEVERITY_LOW_ARB, aMessage);
1498 if (myComputeInitStatus == OpenGl_RT_NONE || aToRebuildShaders)
1500 for (Standard_Integer anIndex = 0; anIndex < 2; ++anIndex)
1502 Handle(OpenGl_ShaderProgram)& aShaderProgram =
1503 (anIndex == 0) ? myRaytraceProgram : myPostFSAAProgram;
1505 myGlContext->BindProgram (aShaderProgram);
1507 aShaderProgram->SetSampler (myGlContext,
1508 "uSceneMinPointTexture", OpenGl_RT_SceneMinPointTexture);
1509 aShaderProgram->SetSampler (myGlContext,
1510 "uSceneMaxPointTexture", OpenGl_RT_SceneMaxPointTexture);
1511 aShaderProgram->SetSampler (myGlContext,
1512 "uSceneNodeInfoTexture", OpenGl_RT_SceneNodeInfoTexture);
1513 aShaderProgram->SetSampler (myGlContext,
1514 "uGeometryVertexTexture", OpenGl_RT_GeometryVertexTexture);
1515 aShaderProgram->SetSampler (myGlContext,
1516 "uGeometryNormalTexture", OpenGl_RT_GeometryNormalTexture);
1517 aShaderProgram->SetSampler (myGlContext,
1518 "uGeometryTexCrdTexture", OpenGl_RT_GeometryTexCrdTexture);
1519 aShaderProgram->SetSampler (myGlContext,
1520 "uGeometryTriangTexture", OpenGl_RT_GeometryTriangTexture);
1521 aShaderProgram->SetSampler (myGlContext,
1522 "uSceneTransformTexture", OpenGl_RT_SceneTransformTexture);
1523 aShaderProgram->SetSampler (myGlContext,
1524 "uEnvironmentMapTexture", OpenGl_RT_EnvironmentMapTexture);
1525 aShaderProgram->SetSampler (myGlContext,
1526 "uRaytraceMaterialTexture", OpenGl_RT_RaytraceMaterialTexture);
1527 aShaderProgram->SetSampler (myGlContext,
1528 "uRaytraceLightSrcTexture", OpenGl_RT_RaytraceLightSrcTexture);
1530 aShaderProgram->SetSampler (myGlContext,
1531 "uOpenGlColorTexture", OpenGl_RT_OpenGlColorTexture);
1532 aShaderProgram->SetSampler (myGlContext,
1533 "uOpenGlDepthTexture", OpenGl_RT_OpenGlDepthTexture);
1537 aShaderProgram->SetSampler (myGlContext,
1538 "uFSAAInputTexture", OpenGl_RT_FSAAInputTexture);
1541 myUniformLocations[anIndex][OpenGl_RT_aPosition] =
1542 aShaderProgram->GetAttributeLocation (myGlContext, "occVertex");
1544 myUniformLocations[anIndex][OpenGl_RT_uOriginLB] =
1545 aShaderProgram->GetUniformLocation (myGlContext, "uOriginLB");
1546 myUniformLocations[anIndex][OpenGl_RT_uOriginRB] =
1547 aShaderProgram->GetUniformLocation (myGlContext, "uOriginRB");
1548 myUniformLocations[anIndex][OpenGl_RT_uOriginLT] =
1549 aShaderProgram->GetUniformLocation (myGlContext, "uOriginLT");
1550 myUniformLocations[anIndex][OpenGl_RT_uOriginRT] =
1551 aShaderProgram->GetUniformLocation (myGlContext, "uOriginRT");
1552 myUniformLocations[anIndex][OpenGl_RT_uDirectLB] =
1553 aShaderProgram->GetUniformLocation (myGlContext, "uDirectLB");
1554 myUniformLocations[anIndex][OpenGl_RT_uDirectRB] =
1555 aShaderProgram->GetUniformLocation (myGlContext, "uDirectRB");
1556 myUniformLocations[anIndex][OpenGl_RT_uDirectLT] =
1557 aShaderProgram->GetUniformLocation (myGlContext, "uDirectLT");
1558 myUniformLocations[anIndex][OpenGl_RT_uDirectRT] =
1559 aShaderProgram->GetUniformLocation (myGlContext, "uDirectRT");
1560 myUniformLocations[anIndex][OpenGl_RT_uUnviewMat] =
1561 aShaderProgram->GetUniformLocation (myGlContext, "uUnviewMat");
1563 myUniformLocations[anIndex][OpenGl_RT_uSceneRad] =
1564 aShaderProgram->GetUniformLocation (myGlContext, "uSceneRadius");
1565 myUniformLocations[anIndex][OpenGl_RT_uSceneEps] =
1566 aShaderProgram->GetUniformLocation (myGlContext, "uSceneEpsilon");
1567 myUniformLocations[anIndex][OpenGl_RT_uLightCount] =
1568 aShaderProgram->GetUniformLocation (myGlContext, "uLightCount");
1569 myUniformLocations[anIndex][OpenGl_RT_uLightAmbnt] =
1570 aShaderProgram->GetUniformLocation (myGlContext, "uGlobalAmbient");
1572 myUniformLocations[anIndex][OpenGl_RT_uOffsetX] =
1573 aShaderProgram->GetUniformLocation (myGlContext, "uOffsetX");
1574 myUniformLocations[anIndex][OpenGl_RT_uOffsetY] =
1575 aShaderProgram->GetUniformLocation (myGlContext, "uOffsetY");
1576 myUniformLocations[anIndex][OpenGl_RT_uSamples] =
1577 aShaderProgram->GetUniformLocation (myGlContext, "uSamples");
1578 myUniformLocations[anIndex][OpenGl_RT_uWinSizeX] =
1579 aShaderProgram->GetUniformLocation (myGlContext, "uWinSizeX");
1580 myUniformLocations[anIndex][OpenGl_RT_uWinSizeY] =
1581 aShaderProgram->GetUniformLocation (myGlContext, "uWinSizeY");
1583 myUniformLocations[anIndex][OpenGl_RT_uTextures] =
1584 aShaderProgram->GetUniformLocation (myGlContext, "uTextureSamplers");
1586 myUniformLocations[anIndex][OpenGl_RT_uShadEnabled] =
1587 aShaderProgram->GetUniformLocation (myGlContext, "uShadowsEnable");
1588 myUniformLocations[anIndex][OpenGl_RT_uReflEnabled] =
1589 aShaderProgram->GetUniformLocation (myGlContext, "uReflectionsEnable");
1590 myUniformLocations[anIndex][OpenGl_RT_uEnvMapEnable] =
1591 aShaderProgram->GetUniformLocation (myGlContext, "uEnvironmentEnable");
1594 myGlContext->BindProgram (NULL);
1597 if (myComputeInitStatus != OpenGl_RT_NONE)
1599 return myComputeInitStatus == OpenGl_RT_INIT;
1602 if (myRaytraceFBO1.IsNull())
1604 myRaytraceFBO1 = new OpenGl_FrameBuffer;
1607 if (myRaytraceFBO2.IsNull())
1609 myRaytraceFBO2 = new OpenGl_FrameBuffer;
1612 const GLfloat aVertices[] = { -1.f, -1.f, 0.f,
1619 myRaytraceScreenQuad.Init (myGlContext, 3, 6, aVertices);
1621 myComputeInitStatus = OpenGl_RT_INIT; // initialized in normal way
1623 return Standard_True;
1626 // =======================================================================
1627 // function : NullifyResource
1629 // =======================================================================
1630 inline void NullifyResource (const Handle(OpenGl_Context)& theContext,
1631 Handle(OpenGl_Resource)& theResource)
1633 if (!theResource.IsNull())
1635 theResource->Release (theContext.operator->());
1636 theResource.Nullify();
1640 // =======================================================================
1641 // function : ReleaseRaytraceResources
1642 // purpose : Releases OpenGL/GLSL shader programs
1643 // =======================================================================
1644 void OpenGl_Workspace::ReleaseRaytraceResources()
1646 NullifyResource (myGlContext, myOpenGlFBO);
1647 NullifyResource (myGlContext, myRaytraceFBO1);
1648 NullifyResource (myGlContext, myRaytraceFBO2);
1650 NullifyResource (myGlContext, myRaytraceShader);
1651 NullifyResource (myGlContext, myPostFSAAShader);
1653 NullifyResource (myGlContext, myRaytraceProgram);
1654 NullifyResource (myGlContext, myPostFSAAProgram);
1656 NullifyResource (myGlContext, mySceneNodeInfoTexture);
1657 NullifyResource (myGlContext, mySceneMinPointTexture);
1658 NullifyResource (myGlContext, mySceneMaxPointTexture);
1660 NullifyResource (myGlContext, myGeometryVertexTexture);
1661 NullifyResource (myGlContext, myGeometryNormalTexture);
1662 NullifyResource (myGlContext, myGeometryTexCrdTexture);
1663 NullifyResource (myGlContext, myGeometryTriangTexture);
1664 NullifyResource (myGlContext, mySceneTransformTexture);
1666 NullifyResource (myGlContext, myRaytraceLightSrcTexture);
1667 NullifyResource (myGlContext, myRaytraceMaterialTexture);
1669 if (myRaytraceScreenQuad.IsValid())
1670 myRaytraceScreenQuad.Release (myGlContext.operator->());
1673 // =======================================================================
1674 // function : UploadRaytraceData
1675 // purpose : Uploads ray-trace data to the GPU
1676 // =======================================================================
1677 Standard_Boolean OpenGl_Workspace::UploadRaytraceData()
1679 if (!myGlContext->IsGlGreaterEqual (3, 1))
1681 #ifdef RAY_TRACE_PRINT_INFO
1682 std::cout << "Error: OpenGL version is less than 3.1" << std::endl;
1684 return Standard_False;
1687 /////////////////////////////////////////////////////////////////////////////
1688 // Prepare OpenGL textures
1690 if (myGlContext->arbTexBindless != NULL)
1692 // If OpenGL driver supports bindless textures we need
1693 // to get unique 64- bit handles for using on the GPU
1694 if (!myRaytraceGeometry.UpdateTextureHandles (myGlContext))
1696 #ifdef RAY_TRACE_PRINT_INFO
1697 std::cout << "Error: Failed to get OpenGL texture handles" << std::endl;
1699 return Standard_False;
1703 /////////////////////////////////////////////////////////////////////////////
1704 // Create OpenGL BVH buffers
1706 if (mySceneNodeInfoTexture.IsNull()) // create scene BVH buffers
1708 mySceneNodeInfoTexture = new OpenGl_TextureBufferArb;
1709 mySceneMinPointTexture = new OpenGl_TextureBufferArb;
1710 mySceneMaxPointTexture = new OpenGl_TextureBufferArb;
1711 mySceneTransformTexture = new OpenGl_TextureBufferArb;
1713 if (!mySceneNodeInfoTexture->Create (myGlContext)
1714 || !mySceneMinPointTexture->Create (myGlContext)
1715 || !mySceneMaxPointTexture->Create (myGlContext)
1716 || !mySceneTransformTexture->Create (myGlContext))
1718 #ifdef RAY_TRACE_PRINT_INFO
1719 std::cout << "Error: Failed to create scene BVH buffers" << std::endl;
1721 return Standard_False;
1725 if (myGeometryVertexTexture.IsNull()) // create geometry buffers
1727 myGeometryVertexTexture = new OpenGl_TextureBufferArb;
1728 myGeometryNormalTexture = new OpenGl_TextureBufferArb;
1729 myGeometryTexCrdTexture = new OpenGl_TextureBufferArb;
1730 myGeometryTriangTexture = new OpenGl_TextureBufferArb;
1732 if (!myGeometryVertexTexture->Create (myGlContext)
1733 || !myGeometryNormalTexture->Create (myGlContext)
1734 || !myGeometryTexCrdTexture->Create (myGlContext)
1735 || !myGeometryTriangTexture->Create (myGlContext))
1737 #ifdef RAY_TRACE_PRINT_INFO
1738 std::cout << "Error: Failed to create buffers for triangulation data" << std::endl;
1740 return Standard_False;
1744 if (myRaytraceMaterialTexture.IsNull()) // create material buffer
1746 myRaytraceMaterialTexture = new OpenGl_TextureBufferArb;
1748 if (!myRaytraceMaterialTexture->Create (myGlContext))
1750 #ifdef RAY_TRACE_PRINT_INFO
1751 std::cout << "Error: Failed to create buffers for material data" << std::endl;
1753 return Standard_False;
1757 /////////////////////////////////////////////////////////////////////////////
1758 // Write transform buffer
1760 BVH_Mat4f* aNodeTransforms = new BVH_Mat4f[myRaytraceGeometry.Size()];
1762 bool aResult = true;
1764 for (Standard_Integer anElemIndex = 0; anElemIndex < myRaytraceGeometry.Size(); ++anElemIndex)
1766 OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
1767 myRaytraceGeometry.Objects().ChangeValue (anElemIndex).operator->());
1769 const BVH_Transform<Standard_ShortReal, 4>* aTransform =
1770 dynamic_cast<const BVH_Transform<Standard_ShortReal, 4>* > (aTriangleSet->Properties().operator->());
1772 Standard_ASSERT_RETURN (aTransform != NULL,
1773 "OpenGl_TriangleSet does not contain transform", Standard_False);
1775 aNodeTransforms[anElemIndex] = aTransform->Inversed();
1778 aResult &= mySceneTransformTexture->Init (myGlContext, 4,
1779 myRaytraceGeometry.Size() * 4, reinterpret_cast<const GLfloat*> (aNodeTransforms));
1781 delete [] aNodeTransforms;
1783 /////////////////////////////////////////////////////////////////////////////
1784 // Write geometry and bottom-level BVH buffers
1786 Standard_Size aTotalVerticesNb = 0;
1787 Standard_Size aTotalElementsNb = 0;
1788 Standard_Size aTotalBVHNodesNb = 0;
1790 for (Standard_Integer anElemIndex = 0; anElemIndex < myRaytraceGeometry.Size(); ++anElemIndex)
1792 OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
1793 myRaytraceGeometry.Objects().ChangeValue (anElemIndex).operator->());
1795 Standard_ASSERT_RETURN (aTriangleSet != NULL,
1796 "Error: Failed to get triangulation of OpenGL element", Standard_False);
1798 aTotalVerticesNb += aTriangleSet->Vertices.size();
1799 aTotalElementsNb += aTriangleSet->Elements.size();
1801 Standard_ASSERT_RETURN (!aTriangleSet->BVH().IsNull(),
1802 "Error: Failed to get bottom-level BVH of OpenGL element", Standard_False);
1804 aTotalBVHNodesNb += aTriangleSet->BVH()->NodeInfoBuffer().size();
1807 aTotalBVHNodesNb += myRaytraceGeometry.BVH()->NodeInfoBuffer().size();
1809 if (aTotalBVHNodesNb != 0)
1811 aResult &= mySceneNodeInfoTexture->Init (
1812 myGlContext, 4, GLsizei (aTotalBVHNodesNb), static_cast<const GLuint*> (NULL));
1813 aResult &= mySceneMinPointTexture->Init (
1814 myGlContext, 3, GLsizei (aTotalBVHNodesNb), static_cast<const GLfloat*> (NULL));
1815 aResult &= mySceneMaxPointTexture->Init (
1816 myGlContext, 3, GLsizei (aTotalBVHNodesNb), static_cast<const GLfloat*> (NULL));
1821 #ifdef RAY_TRACE_PRINT_INFO
1822 std::cout << "Error: Failed to upload buffers for bottom-level scene BVH" << std::endl;
1824 return Standard_False;
1827 if (aTotalElementsNb != 0)
1829 aResult &= myGeometryTriangTexture->Init (
1830 myGlContext, 4, GLsizei (aTotalElementsNb), static_cast<const GLuint*> (NULL));
1833 if (aTotalVerticesNb != 0)
1835 aResult &= myGeometryVertexTexture->Init (
1836 myGlContext, 3, GLsizei (aTotalVerticesNb), static_cast<const GLfloat*> (NULL));
1837 aResult &= myGeometryNormalTexture->Init (
1838 myGlContext, 3, GLsizei (aTotalVerticesNb), static_cast<const GLfloat*> (NULL));
1839 aResult &= myGeometryTexCrdTexture->Init (
1840 myGlContext, 2, GLsizei (aTotalVerticesNb), static_cast<const GLfloat*> (NULL));
1845 #ifdef RAY_TRACE_PRINT_INFO
1846 std::cout << "Error: Failed to upload buffers for scene geometry" << std::endl;
1848 return Standard_False;
1851 const NCollection_Handle<BVH_Tree<Standard_ShortReal, 3> >& aBVH = myRaytraceGeometry.BVH();
1852 const Standard_Integer aBvhLength = aBVH->Length();
1855 aResult &= mySceneNodeInfoTexture->SubData (myGlContext, 0, aBVH->Length(),
1856 reinterpret_cast<const GLuint*> (&aBVH->NodeInfoBuffer().front()));
1857 aResult &= mySceneMinPointTexture->SubData (myGlContext, 0, aBVH->Length(),
1858 reinterpret_cast<const GLfloat*> (&aBVH->MinPointBuffer().front()));
1859 aResult &= mySceneMaxPointTexture->SubData (myGlContext, 0, aBVH->Length(),
1860 reinterpret_cast<const GLfloat*> (&aBVH->MaxPointBuffer().front()));
1863 for (Standard_Integer aNodeIdx = 0; aNodeIdx < aBVH->Length(); ++aNodeIdx)
1865 if (!aBVH->IsOuter (aNodeIdx))
1868 OpenGl_TriangleSet* aTriangleSet = myRaytraceGeometry.TriangleSet (aNodeIdx);
1870 Standard_ASSERT_RETURN (aTriangleSet != NULL,
1871 "Error: Failed to get triangulation of OpenGL element", Standard_False);
1873 Standard_Integer aBVHOffset = myRaytraceGeometry.AccelerationOffset (aNodeIdx);
1875 Standard_ASSERT_RETURN (aBVHOffset != OpenGl_RaytraceGeometry::INVALID_OFFSET,
1876 "Error: Failed to get offset for bottom-level BVH", Standard_False);
1878 const Standard_Integer aBvhBuffersSize = aTriangleSet->BVH()->Length();
1880 if (aBvhBuffersSize != 0)
1882 aResult &= mySceneNodeInfoTexture->SubData (myGlContext, aBVHOffset, aBvhBuffersSize,
1883 reinterpret_cast<const GLuint*> (&aTriangleSet->BVH()->NodeInfoBuffer().front()));
1884 aResult &= mySceneMinPointTexture->SubData (myGlContext, aBVHOffset, aBvhBuffersSize,
1885 reinterpret_cast<const GLfloat*> (&aTriangleSet->BVH()->MinPointBuffer().front()));
1886 aResult &= mySceneMaxPointTexture->SubData (myGlContext, aBVHOffset, aBvhBuffersSize,
1887 reinterpret_cast<const GLfloat*> (&aTriangleSet->BVH()->MaxPointBuffer().front()));
1890 #ifdef RAY_TRACE_PRINT_INFO
1891 std::cout << "Error: Failed to upload buffers for bottom-level scene BVHs" << std::endl;
1893 return Standard_False;
1897 const Standard_Integer aVerticesOffset = myRaytraceGeometry.VerticesOffset (aNodeIdx);
1899 Standard_ASSERT_RETURN (aVerticesOffset != OpenGl_RaytraceGeometry::INVALID_OFFSET,
1900 "Error: Failed to get offset for triangulation vertices of OpenGL element", Standard_False);
1902 if (!aTriangleSet->Vertices.empty())
1904 aResult &= myGeometryNormalTexture->SubData (myGlContext, aVerticesOffset, GLsizei (aTriangleSet->Normals.size()),
1905 reinterpret_cast<const GLfloat*> (&aTriangleSet->Normals.front()));
1906 aResult &= myGeometryTexCrdTexture->SubData (myGlContext, aVerticesOffset, GLsizei (aTriangleSet->TexCrds.size()),
1907 reinterpret_cast<const GLfloat*> (&aTriangleSet->TexCrds.front()));
1908 aResult &= myGeometryVertexTexture->SubData (myGlContext, aVerticesOffset, GLsizei (aTriangleSet->Vertices.size()),
1909 reinterpret_cast<const GLfloat*> (&aTriangleSet->Vertices.front()));
1912 const Standard_Integer anElementsOffset = myRaytraceGeometry.ElementsOffset (aNodeIdx);
1914 Standard_ASSERT_RETURN (anElementsOffset != OpenGl_RaytraceGeometry::INVALID_OFFSET,
1915 "Error: Failed to get offset for triangulation elements of OpenGL element", Standard_False);
1917 if (!aTriangleSet->Elements.empty())
1919 aResult &= myGeometryTriangTexture->SubData (myGlContext, anElementsOffset, GLsizei (aTriangleSet->Elements.size()),
1920 reinterpret_cast<const GLuint*> (&aTriangleSet->Elements.front()));
1925 #ifdef RAY_TRACE_PRINT_INFO
1926 std::cout << "Error: Failed to upload triangulation buffers for OpenGL element" << std::endl;
1928 return Standard_False;
1932 /////////////////////////////////////////////////////////////////////////////
1933 // Write material buffer
1935 if (myRaytraceGeometry.Materials.size() != 0)
1937 aResult &= myRaytraceMaterialTexture->Init (myGlContext, 4,
1938 GLsizei (myRaytraceGeometry.Materials.size() * 11), myRaytraceGeometry.Materials.front().Packed());
1942 #ifdef RAY_TRACE_PRINT_INFO
1943 std::cout << "Error: Failed to upload material buffer" << std::endl;
1945 return Standard_False;
1949 myIsRaytraceDataValid = myRaytraceGeometry.Objects().Size() != 0;
1951 #ifdef RAY_TRACE_PRINT_INFO
1953 Standard_ShortReal aMemUsed = 0.f;
1955 for (Standard_Integer anElemIdx = 0; anElemIdx < myRaytraceGeometry.Size(); ++anElemIdx)
1957 OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
1958 myRaytraceGeometry.Objects().ChangeValue (anElemIdx).operator->());
1960 aMemUsed += static_cast<Standard_ShortReal> (
1961 aTriangleSet->Vertices.size() * sizeof (BVH_Vec3f));
1962 aMemUsed += static_cast<Standard_ShortReal> (
1963 aTriangleSet->Normals.size() * sizeof (BVH_Vec3f));
1964 aMemUsed += static_cast<Standard_ShortReal> (
1965 aTriangleSet->TexCrds.size() * sizeof (BVH_Vec2f));
1966 aMemUsed += static_cast<Standard_ShortReal> (
1967 aTriangleSet->Elements.size() * sizeof (BVH_Vec4i));
1969 aMemUsed += static_cast<Standard_ShortReal> (
1970 aTriangleSet->BVH()->NodeInfoBuffer().size() * sizeof (BVH_Vec4i));
1971 aMemUsed += static_cast<Standard_ShortReal> (
1972 aTriangleSet->BVH()->MinPointBuffer().size() * sizeof (BVH_Vec3f));
1973 aMemUsed += static_cast<Standard_ShortReal> (
1974 aTriangleSet->BVH()->MaxPointBuffer().size() * sizeof (BVH_Vec3f));
1977 aMemUsed += static_cast<Standard_ShortReal> (
1978 myRaytraceGeometry.BVH()->NodeInfoBuffer().size() * sizeof (BVH_Vec4i));
1979 aMemUsed += static_cast<Standard_ShortReal> (
1980 myRaytraceGeometry.BVH()->MinPointBuffer().size() * sizeof (BVH_Vec3f));
1981 aMemUsed += static_cast<Standard_ShortReal> (
1982 myRaytraceGeometry.BVH()->MaxPointBuffer().size() * sizeof (BVH_Vec3f));
1984 std::cout << "GPU Memory Used (MB): ~" << aMemUsed / 1048576 << std::endl;
1991 // =======================================================================
1992 // function : ResizeRaytraceBuffers
1993 // purpose : Resizes OpenGL frame buffers
1994 // =======================================================================
1995 Standard_Boolean OpenGl_Workspace::ResizeRaytraceBuffers (const Standard_Integer theSizeX,
1996 const Standard_Integer theSizeY)
1998 if (myRaytraceFBO1->GetVPSizeX() != theSizeX
1999 || myRaytraceFBO1->GetVPSizeY() != theSizeY)
2001 myRaytraceFBO1->Init (myGlContext, theSizeX, theSizeY);
2002 myRaytraceFBO2->Init (myGlContext, theSizeX, theSizeY);
2005 return Standard_True;
2008 // =======================================================================
2009 // function : UpdateCamera
2010 // purpose : Generates viewing rays for corners of screen quad
2011 // =======================================================================
2012 void OpenGl_Workspace::UpdateCamera (const OpenGl_Mat4& theOrientation,
2013 const OpenGl_Mat4& theViewMapping,
2014 OpenGl_Vec3 theOrigins[4],
2015 OpenGl_Vec3 theDirects[4],
2016 OpenGl_Mat4& theInvModelProj)
2018 // compute inverse model-view-projection matrix
2019 (theViewMapping * theOrientation).Inverted (theInvModelProj);
2021 Standard_Integer aOriginIndex = 0;
2022 Standard_Integer aDirectIndex = 0;
2024 for (Standard_Integer aY = -1; aY <= 1; aY += 2)
2026 for (Standard_Integer aX = -1; aX <= 1; aX += 2)
2028 OpenGl_Vec4 aOrigin (GLfloat(aX),
2033 aOrigin = theInvModelProj * aOrigin;
2035 aOrigin.x() = aOrigin.x() / aOrigin.w();
2036 aOrigin.y() = aOrigin.y() / aOrigin.w();
2037 aOrigin.z() = aOrigin.z() / aOrigin.w();
2039 OpenGl_Vec4 aDirect (GLfloat(aX),
2044 aDirect = theInvModelProj * aDirect;
2046 aDirect.x() = aDirect.x() / aDirect.w();
2047 aDirect.y() = aDirect.y() / aDirect.w();
2048 aDirect.z() = aDirect.z() / aDirect.w();
2050 aDirect = aDirect - aOrigin;
2052 GLdouble aInvLen = 1.0 / sqrt (aDirect.x() * aDirect.x() +
2053 aDirect.y() * aDirect.y() +
2054 aDirect.z() * aDirect.z());
2056 theOrigins[aOriginIndex++] = OpenGl_Vec3 (static_cast<GLfloat> (aOrigin.x()),
2057 static_cast<GLfloat> (aOrigin.y()),
2058 static_cast<GLfloat> (aOrigin.z()));
2060 theDirects[aDirectIndex++] = OpenGl_Vec3 (static_cast<GLfloat> (aDirect.x() * aInvLen),
2061 static_cast<GLfloat> (aDirect.y() * aInvLen),
2062 static_cast<GLfloat> (aDirect.z() * aInvLen));
2067 // =======================================================================
2068 // function : SetUniformState
2069 // purpose : Sets uniform state for the given ray-tracing shader program
2070 // =======================================================================
2071 Standard_Boolean OpenGl_Workspace::SetUniformState (const Graphic3d_CView& theCView,
2072 const Standard_Integer theSizeX,
2073 const Standard_Integer theSizeY,
2074 const OpenGl_Vec3* theOrigins,
2075 const OpenGl_Vec3* theDirects,
2076 const OpenGl_Mat4& theUnviewMat,
2077 const Standard_Integer theProgramIndex,
2078 Handle(OpenGl_ShaderProgram)& theRaytraceProgram)
2080 if (theRaytraceProgram.IsNull())
2082 return Standard_False;
2085 Standard_Integer aLightSourceBufferSize =
2086 static_cast<Standard_Integer> (myRaytraceGeometry.Sources.size());
2088 Standard_Boolean aResult = Standard_True;
2091 aResult &= theRaytraceProgram->SetUniform (myGlContext,
2092 myUniformLocations[theProgramIndex][OpenGl_RT_uOriginLB], theOrigins[0]);
2093 aResult &= theRaytraceProgram->SetUniform (myGlContext,
2094 myUniformLocations[theProgramIndex][OpenGl_RT_uOriginRB], theOrigins[1]);
2095 aResult &= theRaytraceProgram->SetUniform (myGlContext,
2096 myUniformLocations[theProgramIndex][OpenGl_RT_uOriginLT], theOrigins[2]);
2097 aResult &= theRaytraceProgram->SetUniform (myGlContext,
2098 myUniformLocations[theProgramIndex][OpenGl_RT_uOriginRT], theOrigins[3]);
2099 aResult &= theRaytraceProgram->SetUniform (myGlContext,
2100 myUniformLocations[theProgramIndex][OpenGl_RT_uDirectLB], theDirects[0]);
2101 aResult &= theRaytraceProgram->SetUniform (myGlContext,
2102 myUniformLocations[theProgramIndex][OpenGl_RT_uDirectRB], theDirects[1]);
2103 aResult &= theRaytraceProgram->SetUniform (myGlContext,
2104 myUniformLocations[theProgramIndex][OpenGl_RT_uDirectLT], theDirects[2]);
2105 aResult &= theRaytraceProgram->SetUniform (myGlContext,
2106 myUniformLocations[theProgramIndex][OpenGl_RT_uDirectRT], theDirects[3]);
2107 aResult &= theRaytraceProgram->SetUniform (myGlContext,
2108 myUniformLocations[theProgramIndex][OpenGl_RT_uUnviewMat], theUnviewMat);
2111 aResult &= theRaytraceProgram->SetUniform (myGlContext,
2112 myUniformLocations[theProgramIndex][OpenGl_RT_uWinSizeX], theSizeX);
2113 aResult &= theRaytraceProgram->SetUniform (myGlContext,
2114 myUniformLocations[theProgramIndex][OpenGl_RT_uWinSizeY], theSizeY);
2116 // Set scene parameters
2117 aResult &= theRaytraceProgram->SetUniform (myGlContext,
2118 myUniformLocations[theProgramIndex][OpenGl_RT_uSceneRad], myRaytraceSceneRadius);
2119 aResult &= theRaytraceProgram->SetUniform (myGlContext,
2120 myUniformLocations[theProgramIndex][OpenGl_RT_uSceneEps], myRaytraceSceneEpsilon);
2121 aResult &= theRaytraceProgram->SetUniform (myGlContext,
2122 myUniformLocations[theProgramIndex][OpenGl_RT_uLightCount], aLightSourceBufferSize);
2123 aResult &= theRaytraceProgram->SetUniform (myGlContext,
2124 myUniformLocations[theProgramIndex][OpenGl_RT_uLightAmbnt], myRaytraceGeometry.Ambient);
2126 // Set rendering options
2127 aResult &= theRaytraceProgram->SetUniform (myGlContext,
2128 myUniformLocations[theProgramIndex][OpenGl_RT_uShadEnabled], theCView.RenderParams.IsShadowEnabled ? 1 : 0);
2129 aResult &= theRaytraceProgram->SetUniform (myGlContext,
2130 myUniformLocations[theProgramIndex][OpenGl_RT_uReflEnabled], theCView.RenderParams.IsReflectionEnabled ? 1 : 0);
2132 // Set array of 64-bit texture handles
2133 if (myGlContext->arbTexBindless != NULL && myRaytraceGeometry.HasTextures())
2135 aResult &= theRaytraceProgram->SetUniform (myGlContext, "uTextureSamplers",
2136 static_cast<GLsizei> (myRaytraceGeometry.TextureHandles().size()), &myRaytraceGeometry.TextureHandles()[0]);
2141 #ifdef RAY_TRACE_PRINT_INFO
2142 std::cout << "Info: Not all uniforms were detected (for program " << theProgramIndex << ")" << std::endl;
2149 // =======================================================================
2150 // function : RunRaytraceShaders
2151 // purpose : Runs ray-tracing shader programs
2152 // =======================================================================
2153 Standard_Boolean OpenGl_Workspace::RunRaytraceShaders (const Graphic3d_CView& theCView,
2154 const Standard_Integer theSizeX,
2155 const Standard_Integer theSizeY,
2156 const OpenGl_Vec3 theOrigins[4],
2157 const OpenGl_Vec3 theDirects[4],
2158 const OpenGl_Mat4& theUnviewMat,
2159 OpenGl_FrameBuffer* theFrameBuffer)
2161 mySceneMinPointTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneMinPointTexture);
2162 mySceneMaxPointTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneMaxPointTexture);
2163 mySceneNodeInfoTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneNodeInfoTexture);
2164 myGeometryVertexTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryVertexTexture);
2165 myGeometryNormalTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryNormalTexture);
2166 myGeometryTexCrdTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryTexCrdTexture);
2167 myGeometryTriangTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryTriangTexture);
2168 mySceneTransformTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneTransformTexture);
2169 myRaytraceMaterialTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_RaytraceMaterialTexture);
2170 myRaytraceLightSrcTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_RaytraceLightSrcTexture);
2172 myOpenGlFBO->ColorTexture()->Bind (myGlContext, GL_TEXTURE0 + OpenGl_RT_OpenGlColorTexture);
2173 myOpenGlFBO->DepthStencilTexture()->Bind (myGlContext, GL_TEXTURE0 + OpenGl_RT_OpenGlDepthTexture);
2175 if (theCView.RenderParams.IsAntialiasingEnabled) // render source image to FBO
2177 myRaytraceFBO1->BindBuffer (myGlContext);
2179 glDisable (GL_BLEND);
2182 myGlContext->BindProgram (myRaytraceProgram);
2184 SetUniformState (theCView,
2190 0, // ID of RT program
2193 myGlContext->core20fwd->glEnableVertexAttribArray (Graphic3d_TOA_POS);
2195 myGlContext->core20fwd->glVertexAttribPointer (Graphic3d_TOA_POS, 3, GL_FLOAT, GL_FALSE, 0, NULL);
2196 myGlContext->core15fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
2198 myGlContext->core20fwd->glDisableVertexAttribArray (Graphic3d_TOA_POS);
2200 if (!theCView.RenderParams.IsAntialiasingEnabled)
2202 myGlContext->BindProgram (NULL);
2204 myOpenGlFBO->ColorTexture()->Unbind (myGlContext, GL_TEXTURE0 + OpenGl_RT_OpenGlColorTexture);
2205 myOpenGlFBO->DepthStencilTexture()->Unbind (myGlContext, GL_TEXTURE0 + OpenGl_RT_OpenGlDepthTexture);
2206 mySceneMinPointTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneMinPointTexture);
2207 mySceneMaxPointTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneMaxPointTexture);
2208 mySceneNodeInfoTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneNodeInfoTexture);
2209 myGeometryVertexTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryVertexTexture);
2210 myGeometryNormalTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryNormalTexture);
2211 myGeometryTexCrdTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryTexCrdTexture);
2212 myGeometryTriangTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryTriangTexture);
2213 mySceneTransformTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneTransformTexture);
2214 myRaytraceMaterialTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_RaytraceMaterialTexture);
2215 myRaytraceLightSrcTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_RaytraceLightSrcTexture);
2217 myGlContext->core15fwd->glActiveTexture (GL_TEXTURE0);
2219 return Standard_True;
2222 myRaytraceFBO1->ColorTexture()->Bind (myGlContext, GL_TEXTURE0 + OpenGl_RT_FSAAInputTexture);
2224 myGlContext->BindProgram (myPostFSAAProgram);
2226 SetUniformState (theCView,
2232 1, // ID of FSAA program
2235 myGlContext->core20fwd->glEnableVertexAttribArray (Graphic3d_TOA_POS);
2236 myGlContext->core20fwd->glVertexAttribPointer (Graphic3d_TOA_POS, 3, GL_FLOAT, GL_FALSE, 0, NULL);
2238 // Perform multi-pass adaptive FSAA using ping-pong technique.
2239 // We use 'FLIPTRI' sampling pattern changing for every pixel
2240 // (3 additional samples per pixel, the 1st sample is already
2241 // available from initial ray-traced image).
2242 for (Standard_Integer anIt = 1; anIt < 4; ++anIt)
2244 GLfloat aOffsetX = 1.f / theSizeX;
2245 GLfloat aOffsetY = 1.f / theSizeY;
2263 myPostFSAAProgram->SetUniform (myGlContext,
2264 myUniformLocations[1][OpenGl_RT_uSamples], anIt + 1);
2265 myPostFSAAProgram->SetUniform (myGlContext,
2266 myUniformLocations[1][OpenGl_RT_uOffsetX], aOffsetX);
2267 myPostFSAAProgram->SetUniform (myGlContext,
2268 myUniformLocations[1][OpenGl_RT_uOffsetY], aOffsetY);
2270 Handle(OpenGl_FrameBuffer)& aFramebuffer = anIt % 2 ? myRaytraceFBO2 : myRaytraceFBO1;
2272 if (anIt == 3) // disable FBO on last iteration
2274 glEnable (GL_BLEND);
2276 if (theFrameBuffer != NULL)
2277 theFrameBuffer->BindBuffer (myGlContext);
2281 aFramebuffer->BindBuffer (myGlContext);
2284 myGlContext->core15fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
2286 if (anIt != 3) // set input for the next pass
2288 aFramebuffer->ColorTexture()->Bind (myGlContext, GL_TEXTURE0 + OpenGl_RT_FSAAInputTexture);
2289 aFramebuffer->UnbindBuffer (myGlContext);
2293 myGlContext->core20fwd->glDisableVertexAttribArray (Graphic3d_TOA_POS);
2295 myGlContext->BindProgram (NULL);
2296 myRaytraceFBO1->ColorTexture()->Unbind (myGlContext, GL_TEXTURE0 + OpenGl_RT_FSAAInputTexture);
2297 myOpenGlFBO->ColorTexture()->Unbind (myGlContext, GL_TEXTURE0 + OpenGl_RT_OpenGlColorTexture);
2298 myOpenGlFBO->DepthStencilTexture()->Unbind (myGlContext, GL_TEXTURE0 + OpenGl_RT_OpenGlDepthTexture);
2299 mySceneMinPointTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneMinPointTexture);
2300 mySceneMaxPointTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneMaxPointTexture);
2301 mySceneNodeInfoTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneNodeInfoTexture);
2302 myGeometryVertexTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryVertexTexture);
2303 myGeometryNormalTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryNormalTexture);
2304 myGeometryTexCrdTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryTexCrdTexture);
2305 myGeometryTriangTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryTriangTexture);
2306 mySceneTransformTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneTransformTexture);
2307 myRaytraceMaterialTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_RaytraceMaterialTexture);
2308 myRaytraceLightSrcTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_RaytraceLightSrcTexture);
2310 myGlContext->core15fwd->glActiveTexture (GL_TEXTURE0);
2312 return Standard_True;
2315 // =======================================================================
2316 // function : Raytrace
2317 // purpose : Redraws the window using OpenGL/GLSL ray-tracing
2318 // =======================================================================
2319 Standard_Boolean OpenGl_Workspace::Raytrace (const Graphic3d_CView& theCView,
2320 const Standard_Integer theSizeX,
2321 const Standard_Integer theSizeY,
2322 const Aspect_CLayer2d& theCOverLayer,
2323 const Aspect_CLayer2d& theCUnderLayer,
2324 OpenGl_FrameBuffer* theFrameBuffer)
2326 if (!ResizeRaytraceBuffers (theSizeX, theSizeY))
2327 return Standard_False;
2329 if (!UpdateRaytraceEnvironmentMap())
2330 return Standard_False;
2332 // Get model-view and projection matrices
2333 OpenGl_Mat4 aOrientationMatrix;
2334 OpenGl_Mat4 aViewMappingMatrix;
2336 myView->GetMatrices (aOrientationMatrix,
2337 aViewMappingMatrix);
2339 OpenGl_Mat4 aInvOrientationMatrix;
2340 aOrientationMatrix.Inverted (aInvOrientationMatrix);
2342 if (!UpdateRaytraceLightSources (aInvOrientationMatrix))
2343 return Standard_False;
2345 OpenGl_Vec3 aOrigins[4];
2346 OpenGl_Vec3 aDirects[4];
2347 OpenGl_Mat4 anUnviewMat;
2349 UpdateCamera (aOrientationMatrix,
2355 Standard_Boolean wasBlendingEnabled = glIsEnabled (GL_BLEND);
2356 Standard_Boolean wasDepthTestEnabled = glIsEnabled (GL_DEPTH_TEST);
2358 glDisable (GL_DEPTH_TEST);
2360 if (theFrameBuffer != NULL)
2362 theFrameBuffer->BindBuffer (myGlContext);
2365 if (NamedStatus & OPENGL_NS_WHITEBACK)
2367 glClearColor (1.0f, 1.0f, 1.0f, 1.0f);
2371 glClearColor (myBgColor.rgb[0],
2377 glClear (GL_COLOR_BUFFER_BIT);
2379 myView->DrawBackground (this);
2381 myView->RedrawLayer2d (myPrintContext, this, theCView, theCUnderLayer);
2383 myGlContext->WorldViewState.Push();
2384 myGlContext->ProjectionState.Push();
2386 myGlContext->WorldViewState.SetIdentity();
2387 myGlContext->ProjectionState.SetIdentity();
2389 myGlContext->ApplyProjectionMatrix();
2390 myGlContext->ApplyWorldViewMatrix();
2392 glEnable (GL_BLEND);
2393 glBlendFunc (GL_ONE, GL_SRC_ALPHA);
2395 // Generate ray-traced image
2396 if (myIsRaytraceDataValid)
2398 myRaytraceScreenQuad.Bind (myGlContext);
2400 if (!myRaytraceGeometry.AcquireTextures (myGlContext))
2402 const TCollection_ExtendedString aMessage = "Error: Failed to acquire OpenGL image textures";
2404 myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
2405 GL_DEBUG_TYPE_ERROR_ARB, 0, GL_DEBUG_SEVERITY_MEDIUM_ARB, aMessage);
2408 RunRaytraceShaders (theCView,
2416 if (!myRaytraceGeometry.ReleaseTextures (myGlContext))
2418 const TCollection_ExtendedString aMessage = "Error: Failed to release OpenGL image textures";
2420 myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
2421 GL_DEBUG_TYPE_ERROR_ARB, 0, GL_DEBUG_SEVERITY_MEDIUM_ARB, aMessage);
2424 myRaytraceScreenQuad.Unbind (myGlContext);
2427 if (!wasBlendingEnabled)
2428 glDisable (GL_BLEND);
2430 if (wasDepthTestEnabled)
2431 glEnable (GL_DEPTH_TEST);
2433 myGlContext->WorldViewState.Pop();
2434 myGlContext->ProjectionState.Pop();
2436 myGlContext->ApplyProjectionMatrix();
2439 myView->RedrawTrihedron (this);
2442 const int aMode = 0;
2443 DisplayCallback (theCView, (aMode | OCC_PRE_OVERLAY));
2444 myView->RedrawLayer2d (myPrintContext, this, theCView, theCOverLayer);
2445 DisplayCallback (theCView, aMode);
2446 return Standard_True;
2449 IMPLEMENT_STANDARD_HANDLE(OpenGl_RaytraceFilter, OpenGl_RenderFilter)
2450 IMPLEMENT_STANDARD_RTTIEXT(OpenGl_RaytraceFilter, OpenGl_RenderFilter)
2452 // =======================================================================
2453 // function : CanRender
2455 // =======================================================================
2456 Standard_Boolean OpenGl_RaytraceFilter::CanRender (const OpenGl_Element* theElement)
2458 Standard_Boolean aPrevFilterResult = Standard_True;
2459 if (!myPrevRenderFilter.IsNull())
2461 aPrevFilterResult = myPrevRenderFilter->CanRender(theElement);
2463 return aPrevFilterResult &&
2464 !OpenGl_Raytrace::IsRaytracedElement (theElement);