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 = "Error: Failed to create shader object";
1141 myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
1142 GL_DEBUG_TYPE_ERROR_ARB, 0, GL_DEBUG_SEVERITY_HIGH_ARB, aMessage);
1144 aShader->Release (myGlContext.operator->());
1146 return Handle(OpenGl_ShaderObject)();
1149 if (!aShader->LoadSource (myGlContext, theSource.Source()))
1151 const TCollection_ExtendedString aMessage = "Error: Failed to set shader source";
1153 myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
1154 GL_DEBUG_TYPE_ERROR_ARB, 0, GL_DEBUG_SEVERITY_HIGH_ARB, aMessage);
1156 aShader->Release (myGlContext.operator->());
1158 return Handle(OpenGl_ShaderObject)();
1161 TCollection_AsciiString aBuildLog;
1163 if (!aShader->Compile (myGlContext))
1165 if (aShader->FetchInfoLog (myGlContext, aBuildLog))
1167 const TCollection_ExtendedString aMessage =
1168 TCollection_ExtendedString ("Error: Failed to compile shader object:\n") + aBuildLog;
1170 #ifdef RAY_TRACE_PRINT_INFO
1171 std::cout << aBuildLog << std::endl;
1174 myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
1175 GL_DEBUG_TYPE_ERROR_ARB, 0, GL_DEBUG_SEVERITY_HIGH_ARB, aMessage);
1178 aShader->Release (myGlContext.operator->());
1180 return Handle(OpenGl_ShaderObject)();
1183 #ifdef RAY_TRACE_PRINT_INFO
1184 if (aShader->FetchInfoLog (myGlContext, aBuildLog))
1186 if (!aBuildLog.IsEmpty())
1188 std::cout << aBuildLog << std::endl;
1192 std::cout << "Info: shader build log is empty" << std::endl;
1200 // =======================================================================
1201 // function : SafeFailBack
1202 // purpose : Performs safe exit when shaders initialization fails
1203 // =======================================================================
1204 Standard_Boolean OpenGl_Workspace::SafeFailBack (const TCollection_ExtendedString& theMessage)
1206 myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
1207 GL_DEBUG_TYPE_ERROR_ARB, 0, GL_DEBUG_SEVERITY_HIGH_ARB, theMessage);
1209 myComputeInitStatus = OpenGl_RT_FAIL;
1211 ReleaseRaytraceResources();
1213 return Standard_False;
1216 // =======================================================================
1217 // function : GenerateShaderPrefix
1218 // purpose : Generates shader prefix based on current ray-tracing options
1219 // =======================================================================
1220 TCollection_AsciiString OpenGl_Workspace::GenerateShaderPrefix()
1222 TCollection_AsciiString aPrefixString =
1223 TCollection_AsciiString ("#define STACK_SIZE ") + TCollection_AsciiString (myRaytraceParameters.StackSize) + "\n" +
1224 TCollection_AsciiString ("#define NB_BOUNCES ") + TCollection_AsciiString (myRaytraceParameters.NbBounces);
1226 if (myRaytraceParameters.TransparentShadows)
1228 aPrefixString += TCollection_AsciiString ("\n#define TRANSPARENT_SHADOWS");
1231 // If OpenGL driver supports bindless textures
1232 // activate texturing in ray-tracing mode
1233 if (myGlContext->arbTexBindless != NULL)
1235 aPrefixString += TCollection_AsciiString ("\n#define USE_TEXTURES") +
1236 TCollection_AsciiString ("\n#define MAX_TEX_NUMBER ") + TCollection_AsciiString (OpenGl_RaytraceGeometry::MAX_TEX_NUMBER);
1239 return aPrefixString;
1242 // =======================================================================
1243 // function : InitRaytraceResources
1244 // purpose : Initializes OpenGL/GLSL shader programs
1245 // =======================================================================
1246 Standard_Boolean OpenGl_Workspace::InitRaytraceResources (const Graphic3d_CView& theCView)
1248 Standard_Boolean aToRebuildShaders = Standard_False;
1250 if (myComputeInitStatus == OpenGl_RT_INIT)
1252 if (!myIsRaytraceDataValid)
1253 return Standard_True;
1255 const Standard_Integer aRequiredStackSize =
1256 myRaytraceGeometry.HighLevelTreeDepth() + myRaytraceGeometry.BottomLevelTreeDepth();
1258 if (myRaytraceParameters.StackSize < aRequiredStackSize)
1260 myRaytraceParameters.StackSize = Max (aRequiredStackSize, THE_DEFAULT_STACK_SIZE);
1262 aToRebuildShaders = Standard_True;
1266 if (aRequiredStackSize < myRaytraceParameters.StackSize)
1268 if (myRaytraceParameters.StackSize > THE_DEFAULT_STACK_SIZE)
1270 myRaytraceParameters.StackSize = Max (aRequiredStackSize, THE_DEFAULT_STACK_SIZE);
1271 aToRebuildShaders = Standard_True;
1276 if (theCView.RenderParams.RaytracingDepth != myRaytraceParameters.NbBounces)
1278 myRaytraceParameters.NbBounces = theCView.RenderParams.RaytracingDepth;
1279 aToRebuildShaders = Standard_True;
1282 if (theCView.RenderParams.IsTransparentShadowEnabled != myRaytraceParameters.TransparentShadows)
1284 myRaytraceParameters.TransparentShadows = theCView.RenderParams.IsTransparentShadowEnabled;
1285 aToRebuildShaders = Standard_True;
1288 if (aToRebuildShaders)
1290 #ifdef RAY_TRACE_PRINT_INFO
1291 std::cout << "Info: Rebuild shaders with stack size: " << myRaytraceParameters.StackSize << std::endl;
1294 // Change state to force update all uniforms
1295 ++myViewModificationStatus;
1297 TCollection_AsciiString aPrefixString = GenerateShaderPrefix();
1299 #ifdef RAY_TRACE_PRINT_INFO
1300 std::cout << "GLSL prefix string:" << std::endl << aPrefixString << std::endl;
1303 myRaytraceShaderSource.SetPrefix (aPrefixString);
1304 myPostFSAAShaderSource.SetPrefix (aPrefixString);
1306 if (!myRaytraceShader->LoadSource (myGlContext, myRaytraceShaderSource.Source())
1307 || !myPostFSAAShader->LoadSource (myGlContext, myPostFSAAShaderSource.Source()))
1309 return Standard_False;
1312 if (!myRaytraceShader->Compile (myGlContext)
1313 || !myPostFSAAShader->Compile (myGlContext))
1315 return Standard_False;
1318 myRaytraceProgram->SetAttributeName (myGlContext, Graphic3d_TOA_POS, "occVertex");
1319 myPostFSAAProgram->SetAttributeName (myGlContext, Graphic3d_TOA_POS, "occVertex");
1320 if (!myRaytraceProgram->Link (myGlContext)
1321 || !myPostFSAAProgram->Link (myGlContext))
1323 return Standard_False;
1328 if (myComputeInitStatus == OpenGl_RT_NONE)
1330 if (!myGlContext->IsGlGreaterEqual (3, 1))
1332 myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
1333 GL_DEBUG_TYPE_ERROR_ARB, 0, GL_DEBUG_SEVERITY_HIGH_ARB,
1334 "Ray-tracing requires OpenGL 3.1 and higher");
1335 return Standard_False;
1337 else if (!myGlContext->arbTboRGB32)
1339 myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
1340 GL_DEBUG_TYPE_ERROR_ARB, 0, GL_DEBUG_SEVERITY_HIGH_ARB,
1341 "Ray-tracing requires OpenGL 4.0+ or GL_ARB_texture_buffer_object_rgb32 extension");
1342 return Standard_False;
1345 myRaytraceParameters.NbBounces = theCView.RenderParams.RaytracingDepth;
1347 TCollection_AsciiString aFolder = Graphic3d_ShaderProgram::ShadersFolder();
1349 if (aFolder.IsEmpty())
1351 const TCollection_ExtendedString aMessage = "Failed to locate shaders directory";
1353 myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
1354 GL_DEBUG_TYPE_ERROR_ARB, 0, GL_DEBUG_SEVERITY_HIGH_ARB, aMessage);
1356 return Standard_False;
1359 if (myIsRaytraceDataValid)
1361 myRaytraceParameters.StackSize = Max (THE_DEFAULT_STACK_SIZE,
1362 myRaytraceGeometry.HighLevelTreeDepth() + myRaytraceGeometry.BottomLevelTreeDepth());
1365 TCollection_AsciiString aPrefixString = GenerateShaderPrefix();
1367 #ifdef RAY_TRACE_PRINT_INFO
1368 std::cout << "GLSL prefix string:" << std::endl << aPrefixString << std::endl;
1372 Handle(OpenGl_ShaderObject) aBasicVertShader = LoadShader (
1373 ShaderSource (aFolder + "/RaytraceBase.vs"), GL_VERTEX_SHADER);
1375 if (aBasicVertShader.IsNull())
1377 return SafeFailBack ("Failed to set vertex shader source");
1380 TCollection_AsciiString aFiles[] = { aFolder + "/RaytraceBase.fs", aFolder + "/RaytraceRender.fs" };
1382 myRaytraceShaderSource.Load (aFiles, 2);
1384 myRaytraceShaderSource.SetPrefix (aPrefixString);
1386 myRaytraceShader = LoadShader (myRaytraceShaderSource, GL_FRAGMENT_SHADER);
1388 if (myRaytraceShader.IsNull())
1390 aBasicVertShader->Release (myGlContext.operator->());
1392 return SafeFailBack ("Failed to set ray-trace fragment shader source");
1395 myRaytraceProgram = new OpenGl_ShaderProgram;
1397 if (!myRaytraceProgram->Create (myGlContext))
1399 aBasicVertShader->Release (myGlContext.operator->());
1401 return SafeFailBack ("Failed to create ray-trace shader program");
1404 if (!myRaytraceProgram->AttachShader (myGlContext, aBasicVertShader)
1405 || !myRaytraceProgram->AttachShader (myGlContext, myRaytraceShader))
1407 aBasicVertShader->Release (myGlContext.operator->());
1409 return SafeFailBack ("Failed to attach ray-trace shader objects");
1412 myRaytraceProgram->SetAttributeName (myGlContext, Graphic3d_TOA_POS, "occVertex");
1413 if (!myRaytraceProgram->Link (myGlContext))
1415 TCollection_AsciiString aLinkLog;
1417 if (myRaytraceProgram->FetchInfoLog (myGlContext, aLinkLog))
1419 #ifdef RAY_TRACE_PRINT_INFO
1420 std::cout << aLinkLog << std::endl;
1424 return SafeFailBack ("Failed to link ray-trace shader program");
1429 Handle(OpenGl_ShaderObject) aBasicVertShader = LoadShader (
1430 ShaderSource (aFolder + "/RaytraceBase.vs"), GL_VERTEX_SHADER);
1432 if (aBasicVertShader.IsNull())
1434 return SafeFailBack ("Failed to set vertex shader source");
1437 TCollection_AsciiString aFiles[] = { aFolder + "/RaytraceBase.fs", aFolder + "/RaytraceSmooth.fs" };
1439 myPostFSAAShaderSource.Load (aFiles, 2);
1441 myPostFSAAShaderSource.SetPrefix (aPrefixString);
1443 myPostFSAAShader = LoadShader (myPostFSAAShaderSource, GL_FRAGMENT_SHADER);
1445 if (myPostFSAAShader.IsNull())
1447 aBasicVertShader->Release (myGlContext.operator->());
1449 return SafeFailBack ("Failed to set FSAA fragment shader source");
1452 myPostFSAAProgram = new OpenGl_ShaderProgram;
1454 if (!myPostFSAAProgram->Create (myGlContext))
1456 aBasicVertShader->Release (myGlContext.operator->());
1458 return SafeFailBack ("Failed to create FSAA shader program");
1461 if (!myPostFSAAProgram->AttachShader (myGlContext, aBasicVertShader)
1462 || !myPostFSAAProgram->AttachShader (myGlContext, myPostFSAAShader))
1464 aBasicVertShader->Release (myGlContext.operator->());
1466 return SafeFailBack ("Failed to attach FSAA shader objects");
1469 myPostFSAAProgram->SetAttributeName (myGlContext, Graphic3d_TOA_POS, "occVertex");
1470 if (!myPostFSAAProgram->Link (myGlContext))
1472 TCollection_AsciiString aLinkLog;
1474 if (myPostFSAAProgram->FetchInfoLog (myGlContext, aLinkLog))
1476 #ifdef RAY_TRACE_PRINT_INFO
1477 std::cout << aLinkLog << std::endl;
1481 return SafeFailBack ("Failed to link FSAA shader program");
1486 if (myComputeInitStatus == OpenGl_RT_NONE || aToRebuildShaders)
1488 for (Standard_Integer anIndex = 0; anIndex < 2; ++anIndex)
1490 Handle(OpenGl_ShaderProgram)& aShaderProgram =
1491 (anIndex == 0) ? myRaytraceProgram : myPostFSAAProgram;
1493 myGlContext->BindProgram (aShaderProgram);
1495 aShaderProgram->SetSampler (myGlContext,
1496 "uSceneMinPointTexture", OpenGl_RT_SceneMinPointTexture);
1497 aShaderProgram->SetSampler (myGlContext,
1498 "uSceneMaxPointTexture", OpenGl_RT_SceneMaxPointTexture);
1499 aShaderProgram->SetSampler (myGlContext,
1500 "uSceneNodeInfoTexture", OpenGl_RT_SceneNodeInfoTexture);
1501 aShaderProgram->SetSampler (myGlContext,
1502 "uGeometryVertexTexture", OpenGl_RT_GeometryVertexTexture);
1503 aShaderProgram->SetSampler (myGlContext,
1504 "uGeometryNormalTexture", OpenGl_RT_GeometryNormalTexture);
1505 aShaderProgram->SetSampler (myGlContext,
1506 "uGeometryTexCrdTexture", OpenGl_RT_GeometryTexCrdTexture);
1507 aShaderProgram->SetSampler (myGlContext,
1508 "uGeometryTriangTexture", OpenGl_RT_GeometryTriangTexture);
1509 aShaderProgram->SetSampler (myGlContext,
1510 "uSceneTransformTexture", OpenGl_RT_SceneTransformTexture);
1511 aShaderProgram->SetSampler (myGlContext,
1512 "uEnvironmentMapTexture", OpenGl_RT_EnvironmentMapTexture);
1513 aShaderProgram->SetSampler (myGlContext,
1514 "uRaytraceMaterialTexture", OpenGl_RT_RaytraceMaterialTexture);
1515 aShaderProgram->SetSampler (myGlContext,
1516 "uRaytraceLightSrcTexture", OpenGl_RT_RaytraceLightSrcTexture);
1518 aShaderProgram->SetSampler (myGlContext,
1519 "uOpenGlColorTexture", OpenGl_RT_OpenGlColorTexture);
1520 aShaderProgram->SetSampler (myGlContext,
1521 "uOpenGlDepthTexture", OpenGl_RT_OpenGlDepthTexture);
1525 aShaderProgram->SetSampler (myGlContext,
1526 "uFSAAInputTexture", OpenGl_RT_FSAAInputTexture);
1529 myUniformLocations[anIndex][OpenGl_RT_aPosition] =
1530 aShaderProgram->GetAttributeLocation (myGlContext, "occVertex");
1532 myUniformLocations[anIndex][OpenGl_RT_uOriginLB] =
1533 aShaderProgram->GetUniformLocation (myGlContext, "uOriginLB");
1534 myUniformLocations[anIndex][OpenGl_RT_uOriginRB] =
1535 aShaderProgram->GetUniformLocation (myGlContext, "uOriginRB");
1536 myUniformLocations[anIndex][OpenGl_RT_uOriginLT] =
1537 aShaderProgram->GetUniformLocation (myGlContext, "uOriginLT");
1538 myUniformLocations[anIndex][OpenGl_RT_uOriginRT] =
1539 aShaderProgram->GetUniformLocation (myGlContext, "uOriginRT");
1540 myUniformLocations[anIndex][OpenGl_RT_uDirectLB] =
1541 aShaderProgram->GetUniformLocation (myGlContext, "uDirectLB");
1542 myUniformLocations[anIndex][OpenGl_RT_uDirectRB] =
1543 aShaderProgram->GetUniformLocation (myGlContext, "uDirectRB");
1544 myUniformLocations[anIndex][OpenGl_RT_uDirectLT] =
1545 aShaderProgram->GetUniformLocation (myGlContext, "uDirectLT");
1546 myUniformLocations[anIndex][OpenGl_RT_uDirectRT] =
1547 aShaderProgram->GetUniformLocation (myGlContext, "uDirectRT");
1548 myUniformLocations[anIndex][OpenGl_RT_uUnviewMat] =
1549 aShaderProgram->GetUniformLocation (myGlContext, "uUnviewMat");
1551 myUniformLocations[anIndex][OpenGl_RT_uSceneRad] =
1552 aShaderProgram->GetUniformLocation (myGlContext, "uSceneRadius");
1553 myUniformLocations[anIndex][OpenGl_RT_uSceneEps] =
1554 aShaderProgram->GetUniformLocation (myGlContext, "uSceneEpsilon");
1555 myUniformLocations[anIndex][OpenGl_RT_uLightCount] =
1556 aShaderProgram->GetUniformLocation (myGlContext, "uLightCount");
1557 myUniformLocations[anIndex][OpenGl_RT_uLightAmbnt] =
1558 aShaderProgram->GetUniformLocation (myGlContext, "uGlobalAmbient");
1560 myUniformLocations[anIndex][OpenGl_RT_uOffsetX] =
1561 aShaderProgram->GetUniformLocation (myGlContext, "uOffsetX");
1562 myUniformLocations[anIndex][OpenGl_RT_uOffsetY] =
1563 aShaderProgram->GetUniformLocation (myGlContext, "uOffsetY");
1564 myUniformLocations[anIndex][OpenGl_RT_uSamples] =
1565 aShaderProgram->GetUniformLocation (myGlContext, "uSamples");
1566 myUniformLocations[anIndex][OpenGl_RT_uWinSizeX] =
1567 aShaderProgram->GetUniformLocation (myGlContext, "uWinSizeX");
1568 myUniformLocations[anIndex][OpenGl_RT_uWinSizeY] =
1569 aShaderProgram->GetUniformLocation (myGlContext, "uWinSizeY");
1571 myUniformLocations[anIndex][OpenGl_RT_uTextures] =
1572 aShaderProgram->GetUniformLocation (myGlContext, "uTextureSamplers");
1574 myUniformLocations[anIndex][OpenGl_RT_uShadEnabled] =
1575 aShaderProgram->GetUniformLocation (myGlContext, "uShadowsEnable");
1576 myUniformLocations[anIndex][OpenGl_RT_uReflEnabled] =
1577 aShaderProgram->GetUniformLocation (myGlContext, "uReflectionsEnable");
1578 myUniformLocations[anIndex][OpenGl_RT_uEnvMapEnable] =
1579 aShaderProgram->GetUniformLocation (myGlContext, "uEnvironmentEnable");
1582 myGlContext->BindProgram (NULL);
1585 if (myComputeInitStatus != OpenGl_RT_NONE)
1587 return myComputeInitStatus == OpenGl_RT_INIT;
1590 if (myRaytraceFBO1.IsNull())
1592 myRaytraceFBO1 = new OpenGl_FrameBuffer;
1595 if (myRaytraceFBO2.IsNull())
1597 myRaytraceFBO2 = new OpenGl_FrameBuffer;
1600 const GLfloat aVertices[] = { -1.f, -1.f, 0.f,
1607 myRaytraceScreenQuad.Init (myGlContext, 3, 6, aVertices);
1609 myComputeInitStatus = OpenGl_RT_INIT; // initialized in normal way
1611 return Standard_True;
1614 // =======================================================================
1615 // function : NullifyResource
1617 // =======================================================================
1618 inline void NullifyResource (const Handle(OpenGl_Context)& theContext,
1619 Handle(OpenGl_Resource)& theResource)
1621 if (!theResource.IsNull())
1623 theResource->Release (theContext.operator->());
1624 theResource.Nullify();
1628 // =======================================================================
1629 // function : ReleaseRaytraceResources
1630 // purpose : Releases OpenGL/GLSL shader programs
1631 // =======================================================================
1632 void OpenGl_Workspace::ReleaseRaytraceResources()
1634 NullifyResource (myGlContext, myOpenGlFBO);
1635 NullifyResource (myGlContext, myRaytraceFBO1);
1636 NullifyResource (myGlContext, myRaytraceFBO2);
1638 NullifyResource (myGlContext, myRaytraceShader);
1639 NullifyResource (myGlContext, myPostFSAAShader);
1641 NullifyResource (myGlContext, myRaytraceProgram);
1642 NullifyResource (myGlContext, myPostFSAAProgram);
1644 NullifyResource (myGlContext, mySceneNodeInfoTexture);
1645 NullifyResource (myGlContext, mySceneMinPointTexture);
1646 NullifyResource (myGlContext, mySceneMaxPointTexture);
1648 NullifyResource (myGlContext, myGeometryVertexTexture);
1649 NullifyResource (myGlContext, myGeometryNormalTexture);
1650 NullifyResource (myGlContext, myGeometryTexCrdTexture);
1651 NullifyResource (myGlContext, myGeometryTriangTexture);
1652 NullifyResource (myGlContext, mySceneTransformTexture);
1654 NullifyResource (myGlContext, myRaytraceLightSrcTexture);
1655 NullifyResource (myGlContext, myRaytraceMaterialTexture);
1657 if (myRaytraceScreenQuad.IsValid())
1658 myRaytraceScreenQuad.Release (myGlContext.operator->());
1661 // =======================================================================
1662 // function : UploadRaytraceData
1663 // purpose : Uploads ray-trace data to the GPU
1664 // =======================================================================
1665 Standard_Boolean OpenGl_Workspace::UploadRaytraceData()
1667 if (!myGlContext->IsGlGreaterEqual (3, 1))
1669 #ifdef RAY_TRACE_PRINT_INFO
1670 std::cout << "Error: OpenGL version is less than 3.1" << std::endl;
1672 return Standard_False;
1675 /////////////////////////////////////////////////////////////////////////////
1676 // Prepare OpenGL textures
1678 if (myGlContext->arbTexBindless != NULL)
1680 // If OpenGL driver supports bindless textures we need
1681 // to get unique 64- bit handles for using on the GPU
1682 if (!myRaytraceGeometry.UpdateTextureHandles (myGlContext))
1684 #ifdef RAY_TRACE_PRINT_INFO
1685 std::cout << "Error: Failed to get OpenGL texture handles" << std::endl;
1687 return Standard_False;
1691 /////////////////////////////////////////////////////////////////////////////
1692 // Create OpenGL BVH buffers
1694 if (mySceneNodeInfoTexture.IsNull()) // create scene BVH buffers
1696 mySceneNodeInfoTexture = new OpenGl_TextureBufferArb;
1697 mySceneMinPointTexture = new OpenGl_TextureBufferArb;
1698 mySceneMaxPointTexture = new OpenGl_TextureBufferArb;
1699 mySceneTransformTexture = new OpenGl_TextureBufferArb;
1701 if (!mySceneNodeInfoTexture->Create (myGlContext)
1702 || !mySceneMinPointTexture->Create (myGlContext)
1703 || !mySceneMaxPointTexture->Create (myGlContext)
1704 || !mySceneTransformTexture->Create (myGlContext))
1706 #ifdef RAY_TRACE_PRINT_INFO
1707 std::cout << "Error: Failed to create scene BVH buffers" << std::endl;
1709 return Standard_False;
1713 if (myGeometryVertexTexture.IsNull()) // create geometry buffers
1715 myGeometryVertexTexture = new OpenGl_TextureBufferArb;
1716 myGeometryNormalTexture = new OpenGl_TextureBufferArb;
1717 myGeometryTexCrdTexture = new OpenGl_TextureBufferArb;
1718 myGeometryTriangTexture = new OpenGl_TextureBufferArb;
1720 if (!myGeometryVertexTexture->Create (myGlContext)
1721 || !myGeometryNormalTexture->Create (myGlContext)
1722 || !myGeometryTexCrdTexture->Create (myGlContext)
1723 || !myGeometryTriangTexture->Create (myGlContext))
1725 #ifdef RAY_TRACE_PRINT_INFO
1726 std::cout << "Error: Failed to create buffers for triangulation data" << std::endl;
1728 return Standard_False;
1732 if (myRaytraceMaterialTexture.IsNull()) // create material buffer
1734 myRaytraceMaterialTexture = new OpenGl_TextureBufferArb;
1736 if (!myRaytraceMaterialTexture->Create (myGlContext))
1738 #ifdef RAY_TRACE_PRINT_INFO
1739 std::cout << "Error: Failed to create buffers for material data" << std::endl;
1741 return Standard_False;
1745 /////////////////////////////////////////////////////////////////////////////
1746 // Write transform buffer
1748 BVH_Mat4f* aNodeTransforms = new BVH_Mat4f[myRaytraceGeometry.Size()];
1750 bool aResult = true;
1752 for (Standard_Integer anElemIndex = 0; anElemIndex < myRaytraceGeometry.Size(); ++anElemIndex)
1754 OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
1755 myRaytraceGeometry.Objects().ChangeValue (anElemIndex).operator->());
1757 const BVH_Transform<Standard_ShortReal, 4>* aTransform =
1758 dynamic_cast<const BVH_Transform<Standard_ShortReal, 4>* > (aTriangleSet->Properties().operator->());
1760 Standard_ASSERT_RETURN (aTransform != NULL,
1761 "OpenGl_TriangleSet does not contain transform", Standard_False);
1763 aNodeTransforms[anElemIndex] = aTransform->Inversed();
1766 aResult &= mySceneTransformTexture->Init (myGlContext, 4,
1767 myRaytraceGeometry.Size() * 4, reinterpret_cast<const GLfloat*> (aNodeTransforms));
1769 delete [] aNodeTransforms;
1771 /////////////////////////////////////////////////////////////////////////////
1772 // Write geometry and bottom-level BVH buffers
1774 Standard_Size aTotalVerticesNb = 0;
1775 Standard_Size aTotalElementsNb = 0;
1776 Standard_Size aTotalBVHNodesNb = 0;
1778 for (Standard_Integer anElemIndex = 0; anElemIndex < myRaytraceGeometry.Size(); ++anElemIndex)
1780 OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
1781 myRaytraceGeometry.Objects().ChangeValue (anElemIndex).operator->());
1783 Standard_ASSERT_RETURN (aTriangleSet != NULL,
1784 "Error: Failed to get triangulation of OpenGL element", Standard_False);
1786 aTotalVerticesNb += aTriangleSet->Vertices.size();
1787 aTotalElementsNb += aTriangleSet->Elements.size();
1789 Standard_ASSERT_RETURN (!aTriangleSet->BVH().IsNull(),
1790 "Error: Failed to get bottom-level BVH of OpenGL element", Standard_False);
1792 aTotalBVHNodesNb += aTriangleSet->BVH()->NodeInfoBuffer().size();
1795 aTotalBVHNodesNb += myRaytraceGeometry.BVH()->NodeInfoBuffer().size();
1797 if (aTotalBVHNodesNb != 0)
1799 aResult &= mySceneNodeInfoTexture->Init (
1800 myGlContext, 4, GLsizei (aTotalBVHNodesNb), static_cast<const GLuint*> (NULL));
1801 aResult &= mySceneMinPointTexture->Init (
1802 myGlContext, 3, GLsizei (aTotalBVHNodesNb), static_cast<const GLfloat*> (NULL));
1803 aResult &= mySceneMaxPointTexture->Init (
1804 myGlContext, 3, GLsizei (aTotalBVHNodesNb), static_cast<const GLfloat*> (NULL));
1809 #ifdef RAY_TRACE_PRINT_INFO
1810 std::cout << "Error: Failed to upload buffers for bottom-level scene BVH" << std::endl;
1812 return Standard_False;
1815 if (aTotalElementsNb != 0)
1817 aResult &= myGeometryTriangTexture->Init (
1818 myGlContext, 4, GLsizei (aTotalElementsNb), static_cast<const GLuint*> (NULL));
1821 if (aTotalVerticesNb != 0)
1823 aResult &= myGeometryVertexTexture->Init (
1824 myGlContext, 3, GLsizei (aTotalVerticesNb), static_cast<const GLfloat*> (NULL));
1825 aResult &= myGeometryNormalTexture->Init (
1826 myGlContext, 3, GLsizei (aTotalVerticesNb), static_cast<const GLfloat*> (NULL));
1827 aResult &= myGeometryTexCrdTexture->Init (
1828 myGlContext, 2, GLsizei (aTotalVerticesNb), static_cast<const GLfloat*> (NULL));
1833 #ifdef RAY_TRACE_PRINT_INFO
1834 std::cout << "Error: Failed to upload buffers for scene geometry" << std::endl;
1836 return Standard_False;
1839 const NCollection_Handle<BVH_Tree<Standard_ShortReal, 3> >& aBVH = myRaytraceGeometry.BVH();
1840 const Standard_Integer aBvhLength = aBVH->Length();
1843 aResult &= mySceneNodeInfoTexture->SubData (myGlContext, 0, aBVH->Length(),
1844 reinterpret_cast<const GLuint*> (&aBVH->NodeInfoBuffer().front()));
1845 aResult &= mySceneMinPointTexture->SubData (myGlContext, 0, aBVH->Length(),
1846 reinterpret_cast<const GLfloat*> (&aBVH->MinPointBuffer().front()));
1847 aResult &= mySceneMaxPointTexture->SubData (myGlContext, 0, aBVH->Length(),
1848 reinterpret_cast<const GLfloat*> (&aBVH->MaxPointBuffer().front()));
1851 for (Standard_Integer aNodeIdx = 0; aNodeIdx < aBVH->Length(); ++aNodeIdx)
1853 if (!aBVH->IsOuter (aNodeIdx))
1856 OpenGl_TriangleSet* aTriangleSet = myRaytraceGeometry.TriangleSet (aNodeIdx);
1858 Standard_ASSERT_RETURN (aTriangleSet != NULL,
1859 "Error: Failed to get triangulation of OpenGL element", Standard_False);
1861 Standard_Integer aBVHOffset = myRaytraceGeometry.AccelerationOffset (aNodeIdx);
1863 Standard_ASSERT_RETURN (aBVHOffset != OpenGl_RaytraceGeometry::INVALID_OFFSET,
1864 "Error: Failed to get offset for bottom-level BVH", Standard_False);
1866 const Standard_Integer aBvhBuffersSize = aTriangleSet->BVH()->Length();
1868 if (aBvhBuffersSize != 0)
1870 aResult &= mySceneNodeInfoTexture->SubData (myGlContext, aBVHOffset, aBvhBuffersSize,
1871 reinterpret_cast<const GLuint*> (&aTriangleSet->BVH()->NodeInfoBuffer().front()));
1872 aResult &= mySceneMinPointTexture->SubData (myGlContext, aBVHOffset, aBvhBuffersSize,
1873 reinterpret_cast<const GLfloat*> (&aTriangleSet->BVH()->MinPointBuffer().front()));
1874 aResult &= mySceneMaxPointTexture->SubData (myGlContext, aBVHOffset, aBvhBuffersSize,
1875 reinterpret_cast<const GLfloat*> (&aTriangleSet->BVH()->MaxPointBuffer().front()));
1878 #ifdef RAY_TRACE_PRINT_INFO
1879 std::cout << "Error: Failed to upload buffers for bottom-level scene BVHs" << std::endl;
1881 return Standard_False;
1885 const Standard_Integer aVerticesOffset = myRaytraceGeometry.VerticesOffset (aNodeIdx);
1887 Standard_ASSERT_RETURN (aVerticesOffset != OpenGl_RaytraceGeometry::INVALID_OFFSET,
1888 "Error: Failed to get offset for triangulation vertices of OpenGL element", Standard_False);
1890 if (!aTriangleSet->Vertices.empty())
1892 aResult &= myGeometryNormalTexture->SubData (myGlContext, aVerticesOffset, GLsizei (aTriangleSet->Normals.size()),
1893 reinterpret_cast<const GLfloat*> (&aTriangleSet->Normals.front()));
1894 aResult &= myGeometryTexCrdTexture->SubData (myGlContext, aVerticesOffset, GLsizei (aTriangleSet->TexCrds.size()),
1895 reinterpret_cast<const GLfloat*> (&aTriangleSet->TexCrds.front()));
1896 aResult &= myGeometryVertexTexture->SubData (myGlContext, aVerticesOffset, GLsizei (aTriangleSet->Vertices.size()),
1897 reinterpret_cast<const GLfloat*> (&aTriangleSet->Vertices.front()));
1900 const Standard_Integer anElementsOffset = myRaytraceGeometry.ElementsOffset (aNodeIdx);
1902 Standard_ASSERT_RETURN (anElementsOffset != OpenGl_RaytraceGeometry::INVALID_OFFSET,
1903 "Error: Failed to get offset for triangulation elements of OpenGL element", Standard_False);
1905 if (!aTriangleSet->Elements.empty())
1907 aResult &= myGeometryTriangTexture->SubData (myGlContext, anElementsOffset, GLsizei (aTriangleSet->Elements.size()),
1908 reinterpret_cast<const GLuint*> (&aTriangleSet->Elements.front()));
1913 #ifdef RAY_TRACE_PRINT_INFO
1914 std::cout << "Error: Failed to upload triangulation buffers for OpenGL element" << std::endl;
1916 return Standard_False;
1920 /////////////////////////////////////////////////////////////////////////////
1921 // Write material buffer
1923 if (myRaytraceGeometry.Materials.size() != 0)
1925 aResult &= myRaytraceMaterialTexture->Init (myGlContext, 4,
1926 GLsizei (myRaytraceGeometry.Materials.size() * 11), myRaytraceGeometry.Materials.front().Packed());
1930 #ifdef RAY_TRACE_PRINT_INFO
1931 std::cout << "Error: Failed to upload material buffer" << std::endl;
1933 return Standard_False;
1937 myIsRaytraceDataValid = myRaytraceGeometry.Objects().Size() != 0;
1939 #ifdef RAY_TRACE_PRINT_INFO
1941 Standard_ShortReal aMemUsed = 0.f;
1943 for (Standard_Integer anElemIdx = 0; anElemIdx < myRaytraceGeometry.Size(); ++anElemIdx)
1945 OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
1946 myRaytraceGeometry.Objects().ChangeValue (anElemIdx).operator->());
1948 aMemUsed += static_cast<Standard_ShortReal> (
1949 aTriangleSet->Vertices.size() * sizeof (BVH_Vec3f));
1950 aMemUsed += static_cast<Standard_ShortReal> (
1951 aTriangleSet->Normals.size() * sizeof (BVH_Vec3f));
1952 aMemUsed += static_cast<Standard_ShortReal> (
1953 aTriangleSet->TexCrds.size() * sizeof (BVH_Vec2f));
1954 aMemUsed += static_cast<Standard_ShortReal> (
1955 aTriangleSet->Elements.size() * sizeof (BVH_Vec4i));
1957 aMemUsed += static_cast<Standard_ShortReal> (
1958 aTriangleSet->BVH()->NodeInfoBuffer().size() * sizeof (BVH_Vec4i));
1959 aMemUsed += static_cast<Standard_ShortReal> (
1960 aTriangleSet->BVH()->MinPointBuffer().size() * sizeof (BVH_Vec3f));
1961 aMemUsed += static_cast<Standard_ShortReal> (
1962 aTriangleSet->BVH()->MaxPointBuffer().size() * sizeof (BVH_Vec3f));
1965 aMemUsed += static_cast<Standard_ShortReal> (
1966 myRaytraceGeometry.BVH()->NodeInfoBuffer().size() * sizeof (BVH_Vec4i));
1967 aMemUsed += static_cast<Standard_ShortReal> (
1968 myRaytraceGeometry.BVH()->MinPointBuffer().size() * sizeof (BVH_Vec3f));
1969 aMemUsed += static_cast<Standard_ShortReal> (
1970 myRaytraceGeometry.BVH()->MaxPointBuffer().size() * sizeof (BVH_Vec3f));
1972 std::cout << "GPU Memory Used (MB): ~" << aMemUsed / 1048576 << std::endl;
1979 // =======================================================================
1980 // function : ResizeRaytraceBuffers
1981 // purpose : Resizes OpenGL frame buffers
1982 // =======================================================================
1983 Standard_Boolean OpenGl_Workspace::ResizeRaytraceBuffers (const Standard_Integer theSizeX,
1984 const Standard_Integer theSizeY)
1986 if (myRaytraceFBO1->GetVPSizeX() != theSizeX
1987 || myRaytraceFBO1->GetVPSizeY() != theSizeY)
1989 myRaytraceFBO1->Init (myGlContext, theSizeX, theSizeY);
1990 myRaytraceFBO2->Init (myGlContext, theSizeX, theSizeY);
1993 return Standard_True;
1996 // =======================================================================
1997 // function : UpdateCamera
1998 // purpose : Generates viewing rays for corners of screen quad
1999 // =======================================================================
2000 void OpenGl_Workspace::UpdateCamera (const OpenGl_Mat4& theOrientation,
2001 const OpenGl_Mat4& theViewMapping,
2002 OpenGl_Vec3 theOrigins[4],
2003 OpenGl_Vec3 theDirects[4],
2004 OpenGl_Mat4& theInvModelProj)
2006 // compute inverse model-view-projection matrix
2007 (theViewMapping * theOrientation).Inverted (theInvModelProj);
2009 Standard_Integer aOriginIndex = 0;
2010 Standard_Integer aDirectIndex = 0;
2012 for (Standard_Integer aY = -1; aY <= 1; aY += 2)
2014 for (Standard_Integer aX = -1; aX <= 1; aX += 2)
2016 OpenGl_Vec4 aOrigin (GLfloat(aX),
2021 aOrigin = theInvModelProj * aOrigin;
2023 aOrigin.x() = aOrigin.x() / aOrigin.w();
2024 aOrigin.y() = aOrigin.y() / aOrigin.w();
2025 aOrigin.z() = aOrigin.z() / aOrigin.w();
2027 OpenGl_Vec4 aDirect (GLfloat(aX),
2032 aDirect = theInvModelProj * aDirect;
2034 aDirect.x() = aDirect.x() / aDirect.w();
2035 aDirect.y() = aDirect.y() / aDirect.w();
2036 aDirect.z() = aDirect.z() / aDirect.w();
2038 aDirect = aDirect - aOrigin;
2040 GLdouble aInvLen = 1.0 / sqrt (aDirect.x() * aDirect.x() +
2041 aDirect.y() * aDirect.y() +
2042 aDirect.z() * aDirect.z());
2044 theOrigins[aOriginIndex++] = OpenGl_Vec3 (static_cast<GLfloat> (aOrigin.x()),
2045 static_cast<GLfloat> (aOrigin.y()),
2046 static_cast<GLfloat> (aOrigin.z()));
2048 theDirects[aDirectIndex++] = OpenGl_Vec3 (static_cast<GLfloat> (aDirect.x() * aInvLen),
2049 static_cast<GLfloat> (aDirect.y() * aInvLen),
2050 static_cast<GLfloat> (aDirect.z() * aInvLen));
2055 // =======================================================================
2056 // function : SetUniformState
2057 // purpose : Sets uniform state for the given ray-tracing shader program
2058 // =======================================================================
2059 Standard_Boolean OpenGl_Workspace::SetUniformState (const Graphic3d_CView& theCView,
2060 const Standard_Integer theSizeX,
2061 const Standard_Integer theSizeY,
2062 const OpenGl_Vec3* theOrigins,
2063 const OpenGl_Vec3* theDirects,
2064 const OpenGl_Mat4& theUnviewMat,
2065 const Standard_Integer theProgramIndex,
2066 Handle(OpenGl_ShaderProgram)& theRaytraceProgram)
2068 if (theRaytraceProgram.IsNull())
2070 return Standard_False;
2073 Standard_Integer aLightSourceBufferSize =
2074 static_cast<Standard_Integer> (myRaytraceGeometry.Sources.size());
2076 Standard_Boolean aResult = Standard_True;
2079 aResult &= theRaytraceProgram->SetUniform (myGlContext,
2080 myUniformLocations[theProgramIndex][OpenGl_RT_uOriginLB], theOrigins[0]);
2081 aResult &= theRaytraceProgram->SetUniform (myGlContext,
2082 myUniformLocations[theProgramIndex][OpenGl_RT_uOriginRB], theOrigins[1]);
2083 aResult &= theRaytraceProgram->SetUniform (myGlContext,
2084 myUniformLocations[theProgramIndex][OpenGl_RT_uOriginLT], theOrigins[2]);
2085 aResult &= theRaytraceProgram->SetUniform (myGlContext,
2086 myUniformLocations[theProgramIndex][OpenGl_RT_uOriginRT], theOrigins[3]);
2087 aResult &= theRaytraceProgram->SetUniform (myGlContext,
2088 myUniformLocations[theProgramIndex][OpenGl_RT_uDirectLB], theDirects[0]);
2089 aResult &= theRaytraceProgram->SetUniform (myGlContext,
2090 myUniformLocations[theProgramIndex][OpenGl_RT_uDirectRB], theDirects[1]);
2091 aResult &= theRaytraceProgram->SetUniform (myGlContext,
2092 myUniformLocations[theProgramIndex][OpenGl_RT_uDirectLT], theDirects[2]);
2093 aResult &= theRaytraceProgram->SetUniform (myGlContext,
2094 myUniformLocations[theProgramIndex][OpenGl_RT_uDirectRT], theDirects[3]);
2095 aResult &= theRaytraceProgram->SetUniform (myGlContext,
2096 myUniformLocations[theProgramIndex][OpenGl_RT_uUnviewMat], theUnviewMat);
2099 aResult &= theRaytraceProgram->SetUniform (myGlContext,
2100 myUniformLocations[theProgramIndex][OpenGl_RT_uWinSizeX], theSizeX);
2101 aResult &= theRaytraceProgram->SetUniform (myGlContext,
2102 myUniformLocations[theProgramIndex][OpenGl_RT_uWinSizeY], theSizeY);
2104 // Set scene parameters
2105 aResult &= theRaytraceProgram->SetUniform (myGlContext,
2106 myUniformLocations[theProgramIndex][OpenGl_RT_uSceneRad], myRaytraceSceneRadius);
2107 aResult &= theRaytraceProgram->SetUniform (myGlContext,
2108 myUniformLocations[theProgramIndex][OpenGl_RT_uSceneEps], myRaytraceSceneEpsilon);
2109 aResult &= theRaytraceProgram->SetUniform (myGlContext,
2110 myUniformLocations[theProgramIndex][OpenGl_RT_uLightCount], aLightSourceBufferSize);
2111 aResult &= theRaytraceProgram->SetUniform (myGlContext,
2112 myUniformLocations[theProgramIndex][OpenGl_RT_uLightAmbnt], myRaytraceGeometry.Ambient);
2114 // Set rendering options
2115 aResult &= theRaytraceProgram->SetUniform (myGlContext,
2116 myUniformLocations[theProgramIndex][OpenGl_RT_uShadEnabled], theCView.RenderParams.IsShadowEnabled ? 1 : 0);
2117 aResult &= theRaytraceProgram->SetUniform (myGlContext,
2118 myUniformLocations[theProgramIndex][OpenGl_RT_uReflEnabled], theCView.RenderParams.IsReflectionEnabled ? 1 : 0);
2120 // Set array of 64-bit texture handles
2121 if (myGlContext->arbTexBindless != NULL && myRaytraceGeometry.HasTextures())
2123 aResult &= theRaytraceProgram->SetUniform (myGlContext, "uTextureSamplers",
2124 static_cast<GLsizei> (myRaytraceGeometry.TextureHandles().size()), &myRaytraceGeometry.TextureHandles()[0]);
2129 #ifdef RAY_TRACE_PRINT_INFO
2130 std::cout << "Info: Not all uniforms were detected (for program " << theProgramIndex << ")" << std::endl;
2137 // =======================================================================
2138 // function : RunRaytraceShaders
2139 // purpose : Runs ray-tracing shader programs
2140 // =======================================================================
2141 Standard_Boolean OpenGl_Workspace::RunRaytraceShaders (const Graphic3d_CView& theCView,
2142 const Standard_Integer theSizeX,
2143 const Standard_Integer theSizeY,
2144 const OpenGl_Vec3 theOrigins[4],
2145 const OpenGl_Vec3 theDirects[4],
2146 const OpenGl_Mat4& theUnviewMat,
2147 OpenGl_FrameBuffer* theFrameBuffer)
2149 mySceneMinPointTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneMinPointTexture);
2150 mySceneMaxPointTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneMaxPointTexture);
2151 mySceneNodeInfoTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneNodeInfoTexture);
2152 myGeometryVertexTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryVertexTexture);
2153 myGeometryNormalTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryNormalTexture);
2154 myGeometryTexCrdTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryTexCrdTexture);
2155 myGeometryTriangTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryTriangTexture);
2156 mySceneTransformTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneTransformTexture);
2157 myRaytraceMaterialTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_RaytraceMaterialTexture);
2158 myRaytraceLightSrcTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_RaytraceLightSrcTexture);
2160 myOpenGlFBO->ColorTexture()->Bind (myGlContext, GL_TEXTURE0 + OpenGl_RT_OpenGlColorTexture);
2161 myOpenGlFBO->DepthStencilTexture()->Bind (myGlContext, GL_TEXTURE0 + OpenGl_RT_OpenGlDepthTexture);
2163 if (theCView.RenderParams.IsAntialiasingEnabled) // render source image to FBO
2165 myRaytraceFBO1->BindBuffer (myGlContext);
2167 glDisable (GL_BLEND);
2170 myGlContext->BindProgram (myRaytraceProgram);
2172 SetUniformState (theCView,
2178 0, // ID of RT program
2181 myGlContext->core20fwd->glEnableVertexAttribArray (Graphic3d_TOA_POS);
2183 myGlContext->core20fwd->glVertexAttribPointer (Graphic3d_TOA_POS, 3, GL_FLOAT, GL_FALSE, 0, NULL);
2184 myGlContext->core15fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
2186 myGlContext->core20fwd->glDisableVertexAttribArray (Graphic3d_TOA_POS);
2188 if (!theCView.RenderParams.IsAntialiasingEnabled)
2190 myGlContext->BindProgram (NULL);
2192 myOpenGlFBO->ColorTexture()->Unbind (myGlContext, GL_TEXTURE0 + OpenGl_RT_OpenGlColorTexture);
2193 myOpenGlFBO->DepthStencilTexture()->Unbind (myGlContext, GL_TEXTURE0 + OpenGl_RT_OpenGlDepthTexture);
2194 mySceneMinPointTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneMinPointTexture);
2195 mySceneMaxPointTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneMaxPointTexture);
2196 mySceneNodeInfoTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneNodeInfoTexture);
2197 myGeometryVertexTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryVertexTexture);
2198 myGeometryNormalTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryNormalTexture);
2199 myGeometryTexCrdTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryTexCrdTexture);
2200 myGeometryTriangTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryTriangTexture);
2201 mySceneTransformTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneTransformTexture);
2202 myRaytraceMaterialTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_RaytraceMaterialTexture);
2203 myRaytraceLightSrcTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_RaytraceLightSrcTexture);
2205 myGlContext->core15fwd->glActiveTexture (GL_TEXTURE0);
2207 return Standard_True;
2210 myRaytraceFBO1->ColorTexture()->Bind (myGlContext, GL_TEXTURE0 + OpenGl_RT_FSAAInputTexture);
2212 myGlContext->BindProgram (myPostFSAAProgram);
2214 SetUniformState (theCView,
2220 1, // ID of FSAA program
2223 myGlContext->core20fwd->glEnableVertexAttribArray (Graphic3d_TOA_POS);
2224 myGlContext->core20fwd->glVertexAttribPointer (Graphic3d_TOA_POS, 3, GL_FLOAT, GL_FALSE, 0, NULL);
2226 // Perform multi-pass adaptive FSAA using ping-pong technique.
2227 // We use 'FLIPTRI' sampling pattern changing for every pixel
2228 // (3 additional samples per pixel, the 1st sample is already
2229 // available from initial ray-traced image).
2230 for (Standard_Integer anIt = 1; anIt < 4; ++anIt)
2232 GLfloat aOffsetX = 1.f / theSizeX;
2233 GLfloat aOffsetY = 1.f / theSizeY;
2251 myPostFSAAProgram->SetUniform (myGlContext,
2252 myUniformLocations[1][OpenGl_RT_uSamples], anIt + 1);
2253 myPostFSAAProgram->SetUniform (myGlContext,
2254 myUniformLocations[1][OpenGl_RT_uOffsetX], aOffsetX);
2255 myPostFSAAProgram->SetUniform (myGlContext,
2256 myUniformLocations[1][OpenGl_RT_uOffsetY], aOffsetY);
2258 Handle(OpenGl_FrameBuffer)& aFramebuffer = anIt % 2 ? myRaytraceFBO2 : myRaytraceFBO1;
2260 if (anIt == 3) // disable FBO on last iteration
2262 glEnable (GL_BLEND);
2264 if (theFrameBuffer != NULL)
2265 theFrameBuffer->BindBuffer (myGlContext);
2269 aFramebuffer->BindBuffer (myGlContext);
2272 myGlContext->core15fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
2274 if (anIt != 3) // set input for the next pass
2276 aFramebuffer->ColorTexture()->Bind (myGlContext, GL_TEXTURE0 + OpenGl_RT_FSAAInputTexture);
2277 aFramebuffer->UnbindBuffer (myGlContext);
2281 myGlContext->core20fwd->glDisableVertexAttribArray (Graphic3d_TOA_POS);
2283 myGlContext->BindProgram (NULL);
2284 myRaytraceFBO1->ColorTexture()->Unbind (myGlContext, GL_TEXTURE0 + OpenGl_RT_FSAAInputTexture);
2285 myOpenGlFBO->ColorTexture()->Unbind (myGlContext, GL_TEXTURE0 + OpenGl_RT_OpenGlColorTexture);
2286 myOpenGlFBO->DepthStencilTexture()->Unbind (myGlContext, GL_TEXTURE0 + OpenGl_RT_OpenGlDepthTexture);
2287 mySceneMinPointTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneMinPointTexture);
2288 mySceneMaxPointTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneMaxPointTexture);
2289 mySceneNodeInfoTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneNodeInfoTexture);
2290 myGeometryVertexTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryVertexTexture);
2291 myGeometryNormalTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryNormalTexture);
2292 myGeometryTexCrdTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryTexCrdTexture);
2293 myGeometryTriangTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryTriangTexture);
2294 mySceneTransformTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneTransformTexture);
2295 myRaytraceMaterialTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_RaytraceMaterialTexture);
2296 myRaytraceLightSrcTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_RaytraceLightSrcTexture);
2298 myGlContext->core15fwd->glActiveTexture (GL_TEXTURE0);
2300 return Standard_True;
2303 // =======================================================================
2304 // function : Raytrace
2305 // purpose : Redraws the window using OpenGL/GLSL ray-tracing
2306 // =======================================================================
2307 Standard_Boolean OpenGl_Workspace::Raytrace (const Graphic3d_CView& theCView,
2308 const Standard_Integer theSizeX,
2309 const Standard_Integer theSizeY,
2310 const Aspect_CLayer2d& theCOverLayer,
2311 const Aspect_CLayer2d& theCUnderLayer,
2312 OpenGl_FrameBuffer* theFrameBuffer)
2314 if (!InitRaytraceResources (theCView))
2315 return Standard_False;
2317 if (!ResizeRaytraceBuffers (theSizeX, theSizeY))
2318 return Standard_False;
2320 if (!UpdateRaytraceEnvironmentMap())
2321 return Standard_False;
2323 // Get model-view and projection matrices
2324 OpenGl_Mat4 aOrientationMatrix;
2325 OpenGl_Mat4 aViewMappingMatrix;
2327 myView->GetMatrices (aOrientationMatrix,
2328 aViewMappingMatrix);
2330 OpenGl_Mat4 aInvOrientationMatrix;
2331 aOrientationMatrix.Inverted (aInvOrientationMatrix);
2333 if (!UpdateRaytraceLightSources (aInvOrientationMatrix))
2334 return Standard_False;
2336 OpenGl_Vec3 aOrigins[4];
2337 OpenGl_Vec3 aDirects[4];
2338 OpenGl_Mat4 anUnviewMat;
2340 UpdateCamera (aOrientationMatrix,
2346 Standard_Boolean wasBlendingEnabled = glIsEnabled (GL_BLEND);
2347 Standard_Boolean wasDepthTestEnabled = glIsEnabled (GL_DEPTH_TEST);
2349 glDisable (GL_DEPTH_TEST);
2351 if (theFrameBuffer != NULL)
2353 theFrameBuffer->BindBuffer (myGlContext);
2356 if (NamedStatus & OPENGL_NS_WHITEBACK)
2358 glClearColor (1.0f, 1.0f, 1.0f, 1.0f);
2362 glClearColor (myBgColor.rgb[0],
2368 glClear (GL_COLOR_BUFFER_BIT);
2370 myView->DrawBackground (this);
2372 myView->RedrawLayer2d (myPrintContext, this, theCView, theCUnderLayer);
2374 myGlContext->WorldViewState.Push();
2375 myGlContext->ProjectionState.Push();
2377 myGlContext->WorldViewState.SetIdentity();
2378 myGlContext->ProjectionState.SetIdentity();
2380 myGlContext->ApplyProjectionMatrix();
2381 myGlContext->ApplyWorldViewMatrix();
2383 glEnable (GL_BLEND);
2384 glBlendFunc (GL_ONE, GL_SRC_ALPHA);
2386 // Generate ray-traced image
2387 if (myIsRaytraceDataValid)
2389 myRaytraceScreenQuad.Bind (myGlContext);
2391 if (!myRaytraceGeometry.AcquireTextures (myGlContext))
2393 const TCollection_ExtendedString aMessage = "Error: Failed to acquire OpenGL image textures";
2395 myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
2396 GL_DEBUG_TYPE_ERROR_ARB, 0, GL_DEBUG_SEVERITY_MEDIUM_ARB, aMessage);
2399 RunRaytraceShaders (theCView,
2407 if (!myRaytraceGeometry.ReleaseTextures (myGlContext))
2409 const TCollection_ExtendedString aMessage = "Error: Failed to release OpenGL image textures";
2411 myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
2412 GL_DEBUG_TYPE_ERROR_ARB, 0, GL_DEBUG_SEVERITY_MEDIUM_ARB, aMessage);
2415 myRaytraceScreenQuad.Unbind (myGlContext);
2418 if (!wasBlendingEnabled)
2419 glDisable (GL_BLEND);
2421 if (wasDepthTestEnabled)
2422 glEnable (GL_DEPTH_TEST);
2424 myGlContext->WorldViewState.Pop();
2425 myGlContext->ProjectionState.Pop();
2427 myGlContext->ApplyProjectionMatrix();
2430 myView->RedrawTrihedron (this);
2433 const int aMode = 0;
2434 DisplayCallback (theCView, (aMode | OCC_PRE_OVERLAY));
2435 myView->RedrawLayer2d (myPrintContext, this, theCView, theCOverLayer);
2436 DisplayCallback (theCView, aMode);
2437 return Standard_True;
2440 IMPLEMENT_STANDARD_HANDLE(OpenGl_RaytraceFilter, OpenGl_RenderFilter)
2441 IMPLEMENT_STANDARD_RTTIEXT(OpenGl_RaytraceFilter, OpenGl_RenderFilter)
2443 // =======================================================================
2444 // function : CanRender
2446 // =======================================================================
2447 Standard_Boolean OpenGl_RaytraceFilter::CanRender (const OpenGl_Element* theElement)
2449 Standard_Boolean aPrevFilterResult = Standard_True;
2450 if (!myPrevRenderFilter.IsNull())
2452 aPrevFilterResult = myPrevRenderFilter->CanRender(theElement);
2454 return aPrevFilterResult &&
2455 !OpenGl_Raytrace::IsRaytracedElement (theElement);