1 // Created on: 2015-02-20
2 // Created by: Denis BOGOLEPOV
3 // Copyright (c) 2015 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_View.hxx>
18 #include <Graphic3d_TextureParams.hxx>
19 #include <OpenGl_PrimitiveArray.hxx>
20 #include <OpenGl_VertexBuffer.hxx>
21 #include <OSD_Protection.hxx>
22 #include <OSD_File.hxx>
24 using namespace OpenGl_Raytrace;
26 //! Use this macro to output ray-tracing debug info
27 // #define RAY_TRACE_PRINT_INFO
29 #ifdef RAY_TRACE_PRINT_INFO
30 #include <OSD_Timer.hxx>
33 // =======================================================================
34 // function : updateRaytraceGeometry
35 // purpose : Updates 3D scene geometry for ray-tracing
36 // =======================================================================
37 Standard_Boolean OpenGl_View::updateRaytraceGeometry (const RaytraceUpdateMode theMode,
38 const Standard_Integer theViewId,
39 const Handle(OpenGl_Context)& theGlContext)
41 // In 'check' mode (OpenGl_GUM_CHECK) the scene geometry is analyzed for
42 // modifications. This is light-weight procedure performed on each frame
43 if (theMode == OpenGl_GUM_CHECK)
45 if (myLayerListState != myZLayers.ModificationState())
47 return updateRaytraceGeometry (OpenGl_GUM_PREPARE, theViewId, theGlContext);
50 else if (theMode == OpenGl_GUM_PREPARE)
52 myRaytraceGeometry.ClearMaterials();
54 myArrayToTrianglesMap.clear();
56 myIsRaytraceDataValid = Standard_False;
59 // The set of processed structures (reflected to ray-tracing)
60 // This set is used to remove out-of-date records from the
61 // hash map of structures
62 std::set<const OpenGl_Structure*> anElements;
64 // Set to store all currently visible OpenGL primitive arrays
65 // applicable for ray-tracing
66 std::set<Standard_Size> anArrayIDs;
68 // Set to store all non-raytracable elements allowing tracking
69 // of changes in OpenGL scene (only for path tracing)
70 std::set<Standard_Integer> aNonRaytraceIDs;
72 const OpenGl_Layer& aLayer = myZLayers.Layer (Graphic3d_ZLayerId_Default);
74 if (aLayer.NbStructures() != 0)
76 const OpenGl_ArrayOfIndexedMapOfStructure& aStructArray = aLayer.ArrayOfStructures();
78 for (Standard_Integer anIndex = 0; anIndex < aStructArray.Length(); ++anIndex)
80 for (OpenGl_IndexedMapOfStructure::Iterator aStructIt (aStructArray (anIndex)); aStructIt.More(); aStructIt.Next())
82 const OpenGl_Structure* aStructure = aStructIt.Value();
84 if (theMode == OpenGl_GUM_CHECK)
86 if (toUpdateStructure (aStructure))
88 return updateRaytraceGeometry (OpenGl_GUM_PREPARE, theViewId, theGlContext);
90 else if (aStructure->IsVisible() && myRaytraceParameters.GlobalIllumination)
92 aNonRaytraceIDs.insert (aStructure->highlight ? aStructure->Id : -aStructure->Id);
95 else if (theMode == OpenGl_GUM_PREPARE)
97 if (!aStructure->IsRaytracable() || !aStructure->IsVisible())
101 else if (!aStructure->ViewAffinity.IsNull() && !aStructure->ViewAffinity->IsVisible (theViewId))
106 for (OpenGl_Structure::GroupIterator aGroupIter (aStructure->DrawGroups()); aGroupIter.More(); aGroupIter.Next())
108 // Extract OpenGL elements from the group (primitives arrays)
109 for (const OpenGl_ElementNode* aNode = aGroupIter.Value()->FirstNode(); aNode != NULL; aNode = aNode->next)
111 OpenGl_PrimitiveArray* aPrimArray = dynamic_cast<OpenGl_PrimitiveArray*> (aNode->elem);
113 if (aPrimArray != NULL)
115 anArrayIDs.insert (aPrimArray->GetUID());
120 else if (theMode == OpenGl_GUM_REBUILD)
122 if (!aStructure->IsRaytracable())
126 else if (addRaytraceStructure (aStructure, theGlContext))
128 anElements.insert (aStructure); // structure was processed
135 if (theMode == OpenGl_GUM_PREPARE)
137 BVH_ObjectSet<Standard_ShortReal, 3>::BVH_ObjectList anUnchangedObjects;
139 // Filter out unchanged objects so only their transformations and materials
140 // will be updated (and newly added objects will be processed from scratch)
141 for (Standard_Integer anObjIdx = 0; anObjIdx < myRaytraceGeometry.Size(); ++anObjIdx)
143 OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
144 myRaytraceGeometry.Objects().ChangeValue (anObjIdx).operator->());
146 if (aTriangleSet == NULL)
151 if (anArrayIDs.find (aTriangleSet->AssociatedPArrayID()) != anArrayIDs.end())
153 anUnchangedObjects.Append (myRaytraceGeometry.Objects().Value (anObjIdx));
155 myArrayToTrianglesMap[aTriangleSet->AssociatedPArrayID()] = aTriangleSet;
159 myRaytraceGeometry.Objects() = anUnchangedObjects;
161 return updateRaytraceGeometry (OpenGl_GUM_REBUILD, theViewId, theGlContext);
163 else if (theMode == OpenGl_GUM_REBUILD)
165 // Actualize the hash map of structures - remove out-of-date records
166 std::map<const OpenGl_Structure*, StructState>::iterator anIter = myStructureStates.begin();
168 while (anIter != myStructureStates.end())
170 if (anElements.find (anIter->first) == anElements.end())
172 myStructureStates.erase (anIter++);
180 // Actualize OpenGL layer list state
181 myLayerListState = myZLayers.ModificationState();
183 // Rebuild two-level acceleration structure
184 myRaytraceGeometry.ProcessAcceleration();
186 myRaytraceSceneRadius = 2.f /* scale factor */ * std::max (
187 myRaytraceGeometry.Box().CornerMin().cwiseAbs().maxComp(),
188 myRaytraceGeometry.Box().CornerMax().cwiseAbs().maxComp());
190 const BVH_Vec3f aSize = myRaytraceGeometry.Box().Size();
192 myRaytraceSceneEpsilon = Max (1.0e-6f, 1.0e-4f * aSize.Modulus());
194 return uploadRaytraceData (theGlContext);
197 if (myRaytraceParameters.GlobalIllumination)
199 Standard_Boolean toRestart =
200 aNonRaytraceIDs.size() != myNonRaytraceStructureIDs.size();
202 for (std::set<Standard_Integer>::iterator anID = aNonRaytraceIDs.begin(); anID != aNonRaytraceIDs.end() && !toRestart; ++anID)
204 if (myNonRaytraceStructureIDs.find (*anID) == myNonRaytraceStructureIDs.end())
206 toRestart = Standard_True;
213 myNonRaytraceStructureIDs = aNonRaytraceIDs;
216 return Standard_True;
219 // =======================================================================
220 // function : toUpdateStructure
221 // purpose : Checks to see if the structure is modified
222 // =======================================================================
223 Standard_Boolean OpenGl_View::toUpdateStructure (const OpenGl_Structure* theStructure)
225 if (!theStructure->IsRaytracable())
227 if (theStructure->ModificationState() > 0)
229 theStructure->ResetModificationState();
231 return Standard_True; // ray-trace element was removed - need to rebuild
234 return Standard_False; // did not contain ray-trace elements
237 std::map<const OpenGl_Structure*, StructState>::iterator aStructState = myStructureStates.find (theStructure);
239 if (aStructState == myStructureStates.end() || aStructState->second.StructureState != theStructure->ModificationState())
241 return Standard_True;
243 else if (theStructure->InstancedStructure() != NULL)
245 return aStructState->second.InstancedState != theStructure->InstancedStructure()->ModificationState();
248 return Standard_False;
251 // =======================================================================
252 // function : buildTextureTransform
253 // purpose : Constructs texture transformation matrix
254 // =======================================================================
255 void buildTextureTransform (const Handle(Graphic3d_TextureParams)& theParams, BVH_Mat4f& theMatrix)
257 theMatrix.InitIdentity();
260 const Graphic3d_Vec2& aScale = theParams->Scale();
262 theMatrix.ChangeValue (0, 0) *= aScale.x();
263 theMatrix.ChangeValue (1, 0) *= aScale.x();
264 theMatrix.ChangeValue (2, 0) *= aScale.x();
265 theMatrix.ChangeValue (3, 0) *= aScale.x();
267 theMatrix.ChangeValue (0, 1) *= aScale.y();
268 theMatrix.ChangeValue (1, 1) *= aScale.y();
269 theMatrix.ChangeValue (2, 1) *= aScale.y();
270 theMatrix.ChangeValue (3, 1) *= aScale.y();
273 const Graphic3d_Vec2 aTrans = -theParams->Translation();
275 theMatrix.ChangeValue (0, 3) = theMatrix.GetValue (0, 0) * aTrans.x() +
276 theMatrix.GetValue (0, 1) * aTrans.y();
278 theMatrix.ChangeValue (1, 3) = theMatrix.GetValue (1, 0) * aTrans.x() +
279 theMatrix.GetValue (1, 1) * aTrans.y();
281 theMatrix.ChangeValue (2, 3) = theMatrix.GetValue (2, 0) * aTrans.x() +
282 theMatrix.GetValue (2, 1) * aTrans.y();
285 const Standard_ShortReal aSin = std::sin (
286 -theParams->Rotation() * static_cast<Standard_ShortReal> (M_PI / 180.0));
287 const Standard_ShortReal aCos = std::cos (
288 -theParams->Rotation() * static_cast<Standard_ShortReal> (M_PI / 180.0));
290 BVH_Mat4f aRotationMat;
291 aRotationMat.SetValue (0, 0, aCos);
292 aRotationMat.SetValue (1, 1, aCos);
293 aRotationMat.SetValue (0, 1, -aSin);
294 aRotationMat.SetValue (1, 0, aSin);
296 theMatrix = theMatrix * aRotationMat;
299 // =======================================================================
300 // function : convertMaterial
301 // purpose : Creates ray-tracing material properties
302 // =======================================================================
303 OpenGl_RaytraceMaterial OpenGl_View::convertMaterial (const OpenGl_AspectFace* theAspect,
304 const Handle(OpenGl_Context)& theGlContext)
306 OpenGl_RaytraceMaterial theMaterial;
308 const OPENGL_SURF_PROP& aProperties = theAspect->IntFront();
310 theMaterial.Ambient = BVH_Vec4f (
311 (aProperties.isphysic ? aProperties.ambcol.rgb[0] : aProperties.matcol.rgb[0]) * aProperties.amb,
312 (aProperties.isphysic ? aProperties.ambcol.rgb[1] : aProperties.matcol.rgb[1]) * aProperties.amb,
313 (aProperties.isphysic ? aProperties.ambcol.rgb[2] : aProperties.matcol.rgb[2]) * aProperties.amb,
316 theMaterial.Diffuse = BVH_Vec4f (
317 (aProperties.isphysic ? aProperties.difcol.rgb[0] : aProperties.matcol.rgb[0]) * aProperties.diff,
318 (aProperties.isphysic ? aProperties.difcol.rgb[1] : aProperties.matcol.rgb[1]) * aProperties.diff,
319 (aProperties.isphysic ? aProperties.difcol.rgb[2] : aProperties.matcol.rgb[2]) * aProperties.diff,
320 -1.f /* no texture */);
322 theMaterial.Specular = BVH_Vec4f (
323 (aProperties.isphysic ? aProperties.speccol.rgb[0] : 1.f) * aProperties.spec,
324 (aProperties.isphysic ? aProperties.speccol.rgb[1] : 1.f) * aProperties.spec,
325 (aProperties.isphysic ? aProperties.speccol.rgb[2] : 1.f) * aProperties.spec,
328 theMaterial.Emission = BVH_Vec4f (
329 (aProperties.isphysic ? aProperties.emscol.rgb[0] : aProperties.matcol.rgb[0]) * aProperties.emsv,
330 (aProperties.isphysic ? aProperties.emscol.rgb[1] : aProperties.matcol.rgb[1]) * aProperties.emsv,
331 (aProperties.isphysic ? aProperties.emscol.rgb[2] : aProperties.matcol.rgb[2]) * aProperties.emsv,
334 theMaterial.Transparency = BVH_Vec4f (aProperties.trans,
335 1.f - aProperties.trans,
336 aProperties.index == 0 ? 1.f : aProperties.index,
337 aProperties.index == 0 ? 1.f : 1.f / aProperties.index);
339 const Standard_ShortReal aMaxRefl = Max (theMaterial.Diffuse.x() + theMaterial.Specular.x(),
340 Max (theMaterial.Diffuse.y() + theMaterial.Specular.y(),
341 theMaterial.Diffuse.z() + theMaterial.Specular.z()));
343 const Standard_ShortReal aReflectionScale = 0.75f / aMaxRefl;
345 theMaterial.Reflection = BVH_Vec4f (
346 aProperties.speccol.rgb[0] * aProperties.spec * aReflectionScale,
347 aProperties.speccol.rgb[1] * aProperties.spec * aReflectionScale,
348 aProperties.speccol.rgb[2] * aProperties.spec * aReflectionScale,
351 // Serialize physically-based material properties
352 const Graphic3d_BSDF& aBSDF = aProperties.BSDF;
354 theMaterial.BSDF.Le = BVH_Vec4f (aBSDF.Le, 0.f);
355 theMaterial.BSDF.Kd = BVH_Vec4f (aBSDF.Kd, -1.f /* no tex */);
356 theMaterial.BSDF.Kr = BVH_Vec4f (aBSDF.Kr, 0.f);
357 theMaterial.BSDF.Kt = BVH_Vec4f (aBSDF.Kt, 0.f);
358 theMaterial.BSDF.Ks = BVH_Vec4f (aBSDF.Ks, aBSDF.Roughness);
360 theMaterial.BSDF.Fresnel = aBSDF.Fresnel.Serialize();
362 theMaterial.BSDF.Absorption = BVH_Vec4f (aBSDF.AbsorptionColor,
363 aBSDF.AbsorptionCoeff);
365 // Handle material textures
366 if (theAspect->DoTextureMap())
368 if (theGlContext->arbTexBindless != NULL)
370 buildTextureTransform (theAspect->TextureParams(), theMaterial.TextureTransform);
372 // write texture ID to diffuse w-component
373 theMaterial.Diffuse.w() = theMaterial.BSDF.Kd.w() =
374 static_cast<Standard_ShortReal> (myRaytraceGeometry.AddTexture (theAspect->TextureRes (theGlContext)));
376 else if (!myIsRaytraceWarnTextures)
378 const TCollection_ExtendedString aWarnMessage =
379 "Warning: texturing in Ray-Trace requires GL_ARB_bindless_texture extension which is missing. "
380 "Please try to update graphics card driver. At the moment textures will be ignored.";
382 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
383 GL_DEBUG_TYPE_PORTABILITY_ARB, 0, GL_DEBUG_SEVERITY_HIGH_ARB, aWarnMessage);
385 myIsRaytraceWarnTextures = Standard_True;
392 // =======================================================================
393 // function : addRaytraceStructure
394 // purpose : Adds OpenGL structure to ray-traced scene geometry
395 // =======================================================================
396 Standard_Boolean OpenGl_View::addRaytraceStructure (const OpenGl_Structure* theStructure,
397 const Handle(OpenGl_Context)& theGlContext)
399 if (!theStructure->IsVisible())
401 myStructureStates[theStructure] = StructState (theStructure);
403 return Standard_True;
406 // Get structure material
407 OpenGl_RaytraceMaterial aStructMaterial;
409 if (theStructure->AspectFace() != NULL)
411 aStructMaterial = convertMaterial (theStructure->AspectFace(), theGlContext);
414 Standard_ShortReal aStructTransform[16];
416 if (theStructure->Transformation()->mat != NULL)
418 for (Standard_Integer i = 0; i < 4; ++i)
420 for (Standard_Integer j = 0; j < 4; ++j)
422 aStructTransform[j * 4 + i] = theStructure->Transformation()->mat[i][j];
427 Standard_Boolean aResult = addRaytraceGroups (theStructure, aStructMaterial,
428 theStructure->Transformation()->mat ? aStructTransform : NULL, theGlContext);
430 // Process all connected OpenGL structures
431 const OpenGl_Structure* anInstanced = theStructure->InstancedStructure();
433 if (anInstanced != NULL && anInstanced->IsRaytracable())
435 aResult &= addRaytraceGroups (anInstanced, aStructMaterial,
436 theStructure->Transformation()->mat ? aStructTransform : NULL, theGlContext);
439 myStructureStates[theStructure] = StructState (theStructure);
444 // =======================================================================
445 // function : addRaytraceGroups
446 // purpose : Adds OpenGL groups to ray-traced scene geometry
447 // =======================================================================
448 Standard_Boolean OpenGl_View::addRaytraceGroups (const OpenGl_Structure* theStructure,
449 const OpenGl_RaytraceMaterial& theStructMat,
450 const Standard_ShortReal* theTransform,
451 const Handle(OpenGl_Context)& theGlContext)
453 for (OpenGl_Structure::GroupIterator aGroupIter (theStructure->DrawGroups()); aGroupIter.More(); aGroupIter.Next())
455 // Get group material
456 OpenGl_RaytraceMaterial aGroupMaterial;
457 if (aGroupIter.Value()->AspectFace() != NULL)
459 aGroupMaterial = convertMaterial (
460 aGroupIter.Value()->AspectFace(), theGlContext);
463 Standard_Integer aMatID = static_cast<Standard_Integer> (myRaytraceGeometry.Materials.size());
465 // Use group material if available, otherwise use structure material
466 myRaytraceGeometry.Materials.push_back (
467 aGroupIter.Value()->AspectFace() != NULL ? aGroupMaterial : theStructMat);
469 // Add OpenGL elements from group (extract primitives arrays and aspects)
470 for (const OpenGl_ElementNode* aNode = aGroupIter.Value()->FirstNode(); aNode != NULL; aNode = aNode->next)
472 OpenGl_AspectFace* anAspect = dynamic_cast<OpenGl_AspectFace*> (aNode->elem);
474 if (anAspect != NULL)
476 aMatID = static_cast<Standard_Integer> (myRaytraceGeometry.Materials.size());
478 OpenGl_RaytraceMaterial aMaterial = convertMaterial (anAspect, theGlContext);
480 myRaytraceGeometry.Materials.push_back (aMaterial);
484 OpenGl_PrimitiveArray* aPrimArray = dynamic_cast<OpenGl_PrimitiveArray*> (aNode->elem);
486 if (aPrimArray != NULL)
488 std::map<Standard_Size, OpenGl_TriangleSet*>::iterator aSetIter = myArrayToTrianglesMap.find (aPrimArray->GetUID());
490 if (aSetIter != myArrayToTrianglesMap.end())
492 OpenGl_TriangleSet* aSet = aSetIter->second;
494 BVH_Transform<Standard_ShortReal, 4>* aTransform = new BVH_Transform<Standard_ShortReal, 4>();
496 if (theTransform != NULL)
498 aTransform->SetTransform (*(reinterpret_cast<const BVH_Mat4f*> (theTransform)));
501 aSet->SetProperties (aTransform);
503 if (aSet->MaterialIndex() != OpenGl_TriangleSet::INVALID_MATERIAL && aSet->MaterialIndex() != aMatID)
505 aSet->SetMaterialIndex (aMatID);
510 NCollection_Handle<BVH_Object<Standard_ShortReal, 3> > aSet =
511 addRaytracePrimitiveArray (aPrimArray, aMatID, 0);
515 BVH_Transform<Standard_ShortReal, 4>* aTransform = new BVH_Transform<Standard_ShortReal, 4>;
517 if (theTransform != NULL)
519 aTransform->SetTransform (*(reinterpret_cast<const BVH_Mat4f*> (theTransform)));
522 aSet->SetProperties (aTransform);
524 myRaytraceGeometry.Objects().Append (aSet);
532 return Standard_True;
535 // =======================================================================
536 // function : addRaytracePrimitiveArray
537 // purpose : Adds OpenGL primitive array to ray-traced scene geometry
538 // =======================================================================
539 OpenGl_TriangleSet* OpenGl_View::addRaytracePrimitiveArray (const OpenGl_PrimitiveArray* theArray,
540 const Standard_Integer theMaterial,
541 const OpenGl_Mat4* theTransform)
543 const Handle(Graphic3d_BoundBuffer)& aBounds = theArray->Bounds();
544 const Handle(Graphic3d_IndexBuffer)& anIndices = theArray->Indices();
545 const Handle(Graphic3d_Buffer)& anAttribs = theArray->Attributes();
547 if (theArray->DrawMode() < GL_TRIANGLES
548 #ifndef GL_ES_VERSION_2_0
549 || theArray->DrawMode() > GL_POLYGON
551 || theArray->DrawMode() > GL_TRIANGLE_FAN
553 || anAttribs.IsNull())
558 OpenGl_Mat4 aNormalMatrix;
560 if (theTransform != NULL)
562 Standard_ASSERT_RETURN (theTransform->Inverted (aNormalMatrix),
563 "Error: Failed to compute normal transformation matrix", NULL);
565 aNormalMatrix.Transpose();
568 OpenGl_TriangleSet* aSet = new OpenGl_TriangleSet (theArray->GetUID());
570 aSet->Vertices.reserve (anAttribs->NbElements);
571 aSet->Normals.reserve (anAttribs->NbElements);
572 aSet->TexCrds.reserve (anAttribs->NbElements);
574 const size_t aVertFrom = aSet->Vertices.size();
576 for (Standard_Integer anAttribIter = 0; anAttribIter < anAttribs->NbAttributes; ++anAttribIter)
578 const Graphic3d_Attribute& anAttrib = anAttribs->Attribute (anAttribIter);
579 const size_t anOffset = anAttribs->AttributeOffset (anAttribIter);
580 if (anAttrib.Id == Graphic3d_TOA_POS)
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->Vertices.push_back (
588 *reinterpret_cast<const Graphic3d_Vec3*> (anAttribs->value (aVertIter) + anOffset));
591 else if (anAttrib.DataType == Graphic3d_TOD_VEC2)
593 for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
595 const Standard_ShortReal* aCoords =
596 reinterpret_cast<const Standard_ShortReal*> (anAttribs->value (aVertIter) + anOffset);
598 aSet->Vertices.push_back (BVH_Vec3f (aCoords[0], aCoords[1], 0.0f));
602 else if (anAttrib.Id == Graphic3d_TOA_NORM)
604 if (anAttrib.DataType == Graphic3d_TOD_VEC3
605 || anAttrib.DataType == Graphic3d_TOD_VEC4)
607 for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
609 aSet->Normals.push_back (
610 *reinterpret_cast<const Graphic3d_Vec3*> (anAttribs->value (aVertIter) + anOffset));
614 else if (anAttrib.Id == Graphic3d_TOA_UV)
616 if (anAttrib.DataType == Graphic3d_TOD_VEC2)
618 for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
620 aSet->TexCrds.push_back (
621 *reinterpret_cast<const Graphic3d_Vec2*> (anAttribs->value (aVertIter) + anOffset));
627 if (aSet->Normals.size() != aSet->Vertices.size())
629 for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
631 aSet->Normals.push_back (BVH_Vec3f());
635 if (aSet->TexCrds.size() != aSet->Vertices.size())
637 for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
639 aSet->TexCrds.push_back (BVH_Vec2f());
643 if (theTransform != NULL)
645 for (size_t aVertIter = aVertFrom; aVertIter < aSet->Vertices.size(); ++aVertIter)
647 BVH_Vec3f& aVertex = aSet->Vertices[aVertIter];
649 BVH_Vec4f aTransVertex = *theTransform *
650 BVH_Vec4f (aVertex.x(), aVertex.y(), aVertex.z(), 1.f);
652 aVertex = BVH_Vec3f (aTransVertex.x(), aTransVertex.y(), aTransVertex.z());
654 for (size_t aVertIter = aVertFrom; aVertIter < aSet->Normals.size(); ++aVertIter)
656 BVH_Vec3f& aNormal = aSet->Normals[aVertIter];
658 BVH_Vec4f aTransNormal = aNormalMatrix *
659 BVH_Vec4f (aNormal.x(), aNormal.y(), aNormal.z(), 0.f);
661 aNormal = BVH_Vec3f (aTransNormal.x(), aTransNormal.y(), aTransNormal.z());
665 if (!aBounds.IsNull())
667 for (Standard_Integer aBound = 0, aBoundStart = 0; aBound < aBounds->NbBounds; ++aBound)
669 const Standard_Integer aVertNum = aBounds->Bounds[aBound];
671 if (!addRaytraceVertexIndices (*aSet, theMaterial, aVertNum, aBoundStart, *theArray))
677 aBoundStart += aVertNum;
682 const Standard_Integer aVertNum = !anIndices.IsNull() ? anIndices->NbElements : anAttribs->NbElements;
684 if (!addRaytraceVertexIndices (*aSet, theMaterial, aVertNum, 0, *theArray))
692 if (aSet->Size() != 0)
700 // =======================================================================
701 // function : addRaytraceVertexIndices
702 // purpose : Adds vertex indices to ray-traced scene geometry
703 // =======================================================================
704 Standard_Boolean OpenGl_View::addRaytraceVertexIndices (OpenGl_TriangleSet& theSet,
705 const Standard_Integer theMatID,
706 const Standard_Integer theCount,
707 const Standard_Integer theOffset,
708 const OpenGl_PrimitiveArray& theArray)
710 switch (theArray.DrawMode())
712 case GL_TRIANGLES: return addRaytraceTriangleArray (theSet, theMatID, theCount, theOffset, theArray.Indices());
713 case GL_TRIANGLE_FAN: return addRaytraceTriangleFanArray (theSet, theMatID, theCount, theOffset, theArray.Indices());
714 case GL_TRIANGLE_STRIP: return addRaytraceTriangleStripArray (theSet, theMatID, theCount, theOffset, theArray.Indices());
715 #if !defined(GL_ES_VERSION_2_0)
716 case GL_QUAD_STRIP: return addRaytraceQuadrangleStripArray (theSet, theMatID, theCount, theOffset, theArray.Indices());
717 case GL_QUADS: return addRaytraceQuadrangleArray (theSet, theMatID, theCount, theOffset, theArray.Indices());
718 case GL_POLYGON: return addRaytracePolygonArray (theSet, theMatID, theCount, theOffset, theArray.Indices());
722 return Standard_False;
725 // =======================================================================
726 // function : addRaytraceTriangleArray
727 // purpose : Adds OpenGL triangle array to ray-traced scene geometry
728 // =======================================================================
729 Standard_Boolean OpenGl_View::addRaytraceTriangleArray (OpenGl_TriangleSet& theSet,
730 const Standard_Integer theMatID,
731 const Standard_Integer theCount,
732 const Standard_Integer theOffset,
733 const Handle(Graphic3d_IndexBuffer)& theIndices)
737 return Standard_True;
740 theSet.Elements.reserve (theSet.Elements.size() + theCount / 3);
742 if (!theIndices.IsNull())
744 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; aVert += 3)
746 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0),
747 theIndices->Index (aVert + 1),
748 theIndices->Index (aVert + 2),
754 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; aVert += 3)
756 theSet.Elements.push_back (BVH_Vec4i (aVert + 0, aVert + 1, aVert + 2, theMatID));
760 return Standard_True;
763 // =======================================================================
764 // function : addRaytraceTriangleFanArray
765 // purpose : Adds OpenGL triangle fan array to ray-traced scene geometry
766 // =======================================================================
767 Standard_Boolean OpenGl_View::addRaytraceTriangleFanArray (OpenGl_TriangleSet& theSet,
768 const Standard_Integer theMatID,
769 const Standard_Integer theCount,
770 const Standard_Integer theOffset,
771 const Handle(Graphic3d_IndexBuffer)& theIndices)
775 return Standard_True;
778 theSet.Elements.reserve (theSet.Elements.size() + theCount - 2);
780 if (!theIndices.IsNull())
782 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
784 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (theOffset),
785 theIndices->Index (aVert + 1),
786 theIndices->Index (aVert + 2),
792 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
794 theSet.Elements.push_back (BVH_Vec4i (theOffset,
801 return Standard_True;
804 // =======================================================================
805 // function : addRaytraceTriangleStripArray
806 // purpose : Adds OpenGL triangle strip array to ray-traced scene geometry
807 // =======================================================================
808 Standard_Boolean OpenGl_View::addRaytraceTriangleStripArray (OpenGl_TriangleSet& theSet,
809 const Standard_Integer theMatID,
810 const Standard_Integer theCount,
811 const Standard_Integer theOffset,
812 const Handle(Graphic3d_IndexBuffer)& theIndices)
816 return Standard_True;
819 theSet.Elements.reserve (theSet.Elements.size() + theCount - 2);
821 if (!theIndices.IsNull())
823 for (Standard_Integer aVert = theOffset, aCW = 0; aVert < theOffset + theCount - 2; ++aVert, aCW = (aCW + 1) % 2)
825 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + aCW ? 1 : 0),
826 theIndices->Index (aVert + aCW ? 0 : 1),
827 theIndices->Index (aVert + 2),
833 for (Standard_Integer aVert = theOffset, aCW = 0; aVert < theOffset + theCount - 2; ++aVert, aCW = (aCW + 1) % 2)
835 theSet.Elements.push_back (BVH_Vec4i (aVert + aCW ? 1 : 0,
842 return Standard_True;
845 // =======================================================================
846 // function : addRaytraceQuadrangleArray
847 // purpose : Adds OpenGL quad array to ray-traced scene geometry
848 // =======================================================================
849 Standard_Boolean OpenGl_View::addRaytraceQuadrangleArray (OpenGl_TriangleSet& theSet,
850 const Standard_Integer theMatID,
851 const Standard_Integer theCount,
852 const Standard_Integer theOffset,
853 const Handle(Graphic3d_IndexBuffer)& theIndices)
857 return Standard_True;
860 theSet.Elements.reserve (theSet.Elements.size() + theCount / 2);
862 if (!theIndices.IsNull())
864 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 4)
866 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0),
867 theIndices->Index (aVert + 1),
868 theIndices->Index (aVert + 2),
870 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0),
871 theIndices->Index (aVert + 2),
872 theIndices->Index (aVert + 3),
878 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 4)
880 theSet.Elements.push_back (BVH_Vec4i (aVert + 0, aVert + 1, aVert + 2,
882 theSet.Elements.push_back (BVH_Vec4i (aVert + 0, aVert + 2, aVert + 3,
887 return Standard_True;
890 // =======================================================================
891 // function : addRaytraceQuadrangleStripArray
892 // purpose : Adds OpenGL quad strip array to ray-traced scene geometry
893 // =======================================================================
894 Standard_Boolean OpenGl_View::addRaytraceQuadrangleStripArray (OpenGl_TriangleSet& theSet,
895 const Standard_Integer theMatID,
896 const Standard_Integer theCount,
897 const Standard_Integer theOffset,
898 const Handle(Graphic3d_IndexBuffer)& theIndices)
902 return Standard_True;
905 theSet.Elements.reserve (theSet.Elements.size() + 2 * theCount - 6);
907 if (!theIndices.IsNull())
909 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 2)
911 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0),
912 theIndices->Index (aVert + 1),
913 theIndices->Index (aVert + 2),
916 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 1),
917 theIndices->Index (aVert + 3),
918 theIndices->Index (aVert + 2),
924 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 2)
926 theSet.Elements.push_back (BVH_Vec4i (aVert + 0,
931 theSet.Elements.push_back (BVH_Vec4i (aVert + 1,
938 return Standard_True;
941 // =======================================================================
942 // function : addRaytracePolygonArray
943 // purpose : Adds OpenGL polygon array to ray-traced scene geometry
944 // =======================================================================
945 Standard_Boolean OpenGl_View::addRaytracePolygonArray (OpenGl_TriangleSet& theSet,
946 const Standard_Integer theMatID,
947 const Standard_Integer theCount,
948 const Standard_Integer theOffset,
949 const Handle(Graphic3d_IndexBuffer)& theIndices)
953 return Standard_True;
956 theSet.Elements.reserve (theSet.Elements.size() + theCount - 2);
958 if (!theIndices.IsNull())
960 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
962 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (theOffset),
963 theIndices->Index (aVert + 1),
964 theIndices->Index (aVert + 2),
970 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
972 theSet.Elements.push_back (BVH_Vec4i (theOffset,
979 return Standard_True;
982 const TCollection_AsciiString OpenGl_View::ShaderSource::EMPTY_PREFIX;
984 // =======================================================================
986 // purpose : Returns shader source combined with prefix
987 // =======================================================================
988 TCollection_AsciiString OpenGl_View::ShaderSource::Source() const
990 const TCollection_AsciiString aVersion = "#version 140";
992 if (myPrefix.IsEmpty())
994 return aVersion + "\n" + mySource;
997 return aVersion + "\n" + myPrefix + "\n" + mySource;
1000 // =======================================================================
1002 // purpose : Loads shader source from specified files
1003 // =======================================================================
1004 Standard_Boolean OpenGl_View::ShaderSource::Load (const TCollection_AsciiString* theFileNames,
1005 const TCollection_AsciiString& thePrefix)
1009 TCollection_AsciiString aMissingFiles;
1010 for (Standard_Integer anIndex = 0; !theFileNames[anIndex].IsEmpty(); ++anIndex)
1012 OSD_File aFile (theFileNames[anIndex]);
1015 aFile.Open (OSD_ReadOnly, OSD_Protection());
1017 if (!aFile.IsOpen())
1019 if (!aMissingFiles.IsEmpty())
1021 aMissingFiles += ", ";
1023 aMissingFiles += TCollection_AsciiString("'") + theFileNames[anIndex] + "'";
1026 else if (!aMissingFiles.IsEmpty())
1032 TCollection_AsciiString aSource;
1033 aFile.Read (aSource, (Standard_Integer) aFile.Size());
1034 if (!aSource.IsEmpty())
1036 mySource += TCollection_AsciiString ("\n") + aSource;
1041 myPrefix = thePrefix;
1042 if (!aMissingFiles.IsEmpty())
1044 myError = TCollection_AsciiString("Shader files ") + aMissingFiles + " are missing or inaccessible";
1045 return Standard_False;
1047 return Standard_True;
1050 // =======================================================================
1051 // function : generateShaderPrefix
1052 // purpose : Generates shader prefix based on current ray-tracing options
1053 // =======================================================================
1054 TCollection_AsciiString OpenGl_View::generateShaderPrefix (const Handle(OpenGl_Context)& theGlContext) const
1056 TCollection_AsciiString aPrefixString =
1057 TCollection_AsciiString ("#define STACK_SIZE ") + TCollection_AsciiString (myRaytraceParameters.StackSize) + "\n" +
1058 TCollection_AsciiString ("#define NB_BOUNCES ") + TCollection_AsciiString (myRaytraceParameters.NbBounces);
1060 if (myRaytraceParameters.TransparentShadows)
1062 aPrefixString += TCollection_AsciiString ("\n#define TRANSPARENT_SHADOWS");
1065 // If OpenGL driver supports bindless textures and texturing
1066 // is actually used, activate texturing in ray-tracing mode
1067 if (myRaytraceParameters.UseBindlessTextures && theGlContext->arbTexBindless != NULL)
1069 aPrefixString += TCollection_AsciiString ("\n#define USE_TEXTURES") +
1070 TCollection_AsciiString ("\n#define MAX_TEX_NUMBER ") + TCollection_AsciiString (OpenGl_RaytraceGeometry::MAX_TEX_NUMBER);
1073 if (myRaytraceParameters.GlobalIllumination)
1075 aPrefixString += TCollection_AsciiString ("\n#define PATH_TRACING");
1078 return aPrefixString;
1081 // =======================================================================
1082 // function : safeFailBack
1083 // purpose : Performs safe exit when shaders initialization fails
1084 // =======================================================================
1085 Standard_Boolean OpenGl_View::safeFailBack (const TCollection_ExtendedString& theMessage,
1086 const Handle(OpenGl_Context)& theGlContext)
1088 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
1089 GL_DEBUG_TYPE_ERROR_ARB, 0, GL_DEBUG_SEVERITY_HIGH_ARB, theMessage);
1091 myRaytraceInitStatus = OpenGl_RT_FAIL;
1093 releaseRaytraceResources (theGlContext);
1095 return Standard_False;
1098 // =======================================================================
1099 // function : initShader
1100 // purpose : Creates new shader object with specified source
1101 // =======================================================================
1102 Handle(OpenGl_ShaderObject) OpenGl_View::initShader (const GLenum theType,
1103 const ShaderSource& theSource,
1104 const Handle(OpenGl_Context)& theGlContext)
1106 Handle(OpenGl_ShaderObject) aShader = new OpenGl_ShaderObject (theType);
1108 if (!aShader->Create (theGlContext))
1110 const TCollection_ExtendedString aMessage = TCollection_ExtendedString ("Error: Failed to create ") +
1111 (theType == GL_VERTEX_SHADER ? "vertex" : "fragment") + " shader object";
1113 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
1114 GL_DEBUG_TYPE_ERROR_ARB, 0, GL_DEBUG_SEVERITY_HIGH_ARB, aMessage);
1116 aShader->Release (theGlContext.operator->());
1118 return Handle(OpenGl_ShaderObject)();
1121 if (!aShader->LoadSource (theGlContext, theSource.Source()))
1123 const TCollection_ExtendedString aMessage = TCollection_ExtendedString ("Error: Failed to set ") +
1124 (theType == GL_VERTEX_SHADER ? "vertex" : "fragment") + " shader source";
1126 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
1127 GL_DEBUG_TYPE_ERROR_ARB, 0, GL_DEBUG_SEVERITY_HIGH_ARB, aMessage);
1129 aShader->Release (theGlContext.operator->());
1131 return Handle(OpenGl_ShaderObject)();
1134 TCollection_AsciiString aBuildLog;
1136 if (!aShader->Compile (theGlContext))
1138 aShader->FetchInfoLog (theGlContext, aBuildLog);
1140 const TCollection_ExtendedString aMessage = TCollection_ExtendedString ("Error: Failed to compile ") +
1141 (theType == GL_VERTEX_SHADER ? "vertex" : "fragment") + " shader object:\n" + aBuildLog;
1143 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
1144 GL_DEBUG_TYPE_ERROR_ARB, 0, GL_DEBUG_SEVERITY_HIGH_ARB, aMessage);
1146 aShader->Release (theGlContext.operator->());
1148 return Handle(OpenGl_ShaderObject)();
1150 else if (theGlContext->caps->glslWarnings)
1152 aShader->FetchInfoLog (theGlContext, aBuildLog);
1154 if (!aBuildLog.IsEmpty() && !aBuildLog.IsEqual ("No errors.\n"))
1156 const TCollection_ExtendedString aMessage = TCollection_ExtendedString (theType == GL_VERTEX_SHADER ?
1157 "Vertex" : "Fragment") + " shader was compiled with following warnings:\n" + aBuildLog;
1159 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
1160 GL_DEBUG_TYPE_PORTABILITY_ARB, 0, GL_DEBUG_SEVERITY_LOW_ARB, aMessage);
1167 // =======================================================================
1168 // function : initProgram
1169 // purpose : Creates GLSL program from the given shader objects
1170 // =======================================================================
1171 Handle(OpenGl_ShaderProgram) OpenGl_View::initProgram (const Handle(OpenGl_Context)& theGlContext,
1172 const Handle(OpenGl_ShaderObject)& theVertShader,
1173 const Handle(OpenGl_ShaderObject)& theFragShader)
1175 Handle(OpenGl_ShaderProgram) aProgram = new OpenGl_ShaderProgram;
1177 if (!aProgram->Create (theGlContext))
1179 theVertShader->Release (theGlContext.operator->());
1181 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
1182 GL_DEBUG_TYPE_ERROR_ARB, 0, GL_DEBUG_SEVERITY_HIGH_ARB, "Failed to create shader program");
1184 return Handle(OpenGl_ShaderProgram)();
1187 if (!aProgram->AttachShader (theGlContext, theVertShader)
1188 || !aProgram->AttachShader (theGlContext, theFragShader))
1190 theVertShader->Release (theGlContext.operator->());
1192 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
1193 GL_DEBUG_TYPE_ERROR_ARB, 0, GL_DEBUG_SEVERITY_HIGH_ARB, "Failed to attach shader objects");
1195 return Handle(OpenGl_ShaderProgram)();
1198 aProgram->SetAttributeName (theGlContext, Graphic3d_TOA_POS, "occVertex");
1200 TCollection_AsciiString aLinkLog;
1202 if (!aProgram->Link (theGlContext))
1204 aProgram->FetchInfoLog (theGlContext, aLinkLog);
1206 const TCollection_ExtendedString aMessage = TCollection_ExtendedString (
1207 "Failed to link shader program:\n") + aLinkLog;
1209 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
1210 GL_DEBUG_TYPE_ERROR_ARB, 0, GL_DEBUG_SEVERITY_HIGH_ARB, aMessage);
1212 return Handle(OpenGl_ShaderProgram)();
1214 else if (theGlContext->caps->glslWarnings)
1216 aProgram->FetchInfoLog (theGlContext, aLinkLog);
1217 if (!aLinkLog.IsEmpty() && !aLinkLog.IsEqual ("No errors.\n"))
1219 const TCollection_ExtendedString aMessage = TCollection_ExtendedString (
1220 "Shader program was linked with following warnings:\n") + aLinkLog;
1222 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
1223 GL_DEBUG_TYPE_PORTABILITY_ARB, 0, GL_DEBUG_SEVERITY_LOW_ARB, aMessage);
1230 // =======================================================================
1231 // function : initRaytraceResources
1232 // purpose : Initializes OpenGL/GLSL shader programs
1233 // =======================================================================
1234 Standard_Boolean OpenGl_View::initRaytraceResources (const Handle(OpenGl_Context)& theGlContext)
1236 if (myRaytraceInitStatus == OpenGl_RT_FAIL)
1238 return Standard_False;
1241 Standard_Boolean aToRebuildShaders = Standard_False;
1243 if (myRaytraceInitStatus == OpenGl_RT_INIT)
1245 if (!myIsRaytraceDataValid)
1246 return Standard_True;
1248 const Standard_Integer aRequiredStackSize =
1249 myRaytraceGeometry.HighLevelTreeDepth() + myRaytraceGeometry.BottomLevelTreeDepth();
1251 if (myRaytraceParameters.StackSize < aRequiredStackSize)
1253 myRaytraceParameters.StackSize = Max (aRequiredStackSize, THE_DEFAULT_STACK_SIZE);
1255 aToRebuildShaders = Standard_True;
1259 if (aRequiredStackSize < myRaytraceParameters.StackSize)
1261 if (myRaytraceParameters.StackSize > THE_DEFAULT_STACK_SIZE)
1263 myRaytraceParameters.StackSize = Max (aRequiredStackSize, THE_DEFAULT_STACK_SIZE);
1264 aToRebuildShaders = Standard_True;
1269 if (myRenderParams.RaytracingDepth != myRaytraceParameters.NbBounces)
1271 myRaytraceParameters.NbBounces = myRenderParams.RaytracingDepth;
1272 aToRebuildShaders = Standard_True;
1275 if (myRaytraceGeometry.HasTextures() != myRaytraceParameters.UseBindlessTextures)
1277 myRaytraceParameters.UseBindlessTextures = myRaytraceGeometry.HasTextures();
1278 aToRebuildShaders = Standard_True;
1281 if (myRenderParams.IsTransparentShadowEnabled != myRaytraceParameters.TransparentShadows)
1283 myRaytraceParameters.TransparentShadows = myRenderParams.IsTransparentShadowEnabled;
1284 aToRebuildShaders = Standard_True;
1287 if (myRenderParams.IsGlobalIlluminationEnabled != myRaytraceParameters.GlobalIllumination)
1289 myRaytraceParameters.GlobalIllumination = myRenderParams.IsGlobalIlluminationEnabled;
1290 aToRebuildShaders = Standard_True;
1293 if (aToRebuildShaders)
1295 // Reject accumulated frames
1298 // We need to update environment texture
1299 myToUpdateEnvironmentMap = Standard_True;
1301 TCollection_AsciiString aPrefixString = generateShaderPrefix (theGlContext);
1303 #ifdef RAY_TRACE_PRINT_INFO
1304 std::cout << "GLSL prefix string:" << std::endl << aPrefixString << std::endl;
1307 myRaytraceShaderSource.SetPrefix (aPrefixString);
1308 myPostFSAAShaderSource.SetPrefix (aPrefixString);
1310 if (!myRaytraceShader->LoadSource (theGlContext, myRaytraceShaderSource.Source())
1311 || !myPostFSAAShader->LoadSource (theGlContext, myPostFSAAShaderSource.Source()))
1313 return safeFailBack ("Failed to load source into ray-tracing fragment shaders", theGlContext);
1316 if (!myRaytraceShader->Compile (theGlContext)
1317 || !myPostFSAAShader->Compile (theGlContext))
1319 return safeFailBack ("Failed to compile ray-tracing fragment shaders", theGlContext);
1322 myRaytraceProgram->SetAttributeName (theGlContext, Graphic3d_TOA_POS, "occVertex");
1323 myPostFSAAProgram->SetAttributeName (theGlContext, Graphic3d_TOA_POS, "occVertex");
1324 if (!myRaytraceProgram->Link (theGlContext)
1325 || !myPostFSAAProgram->Link (theGlContext))
1327 return safeFailBack ("Failed to initialize vertex attributes for ray-tracing program", theGlContext);
1332 if (myRaytraceInitStatus == OpenGl_RT_NONE)
1334 if (!theGlContext->IsGlGreaterEqual (3, 1))
1336 return safeFailBack ("Ray-tracing requires OpenGL 3.1 and higher", theGlContext);
1338 else if (!theGlContext->arbTboRGB32)
1340 return safeFailBack ("Ray-tracing requires OpenGL 4.0+ or GL_ARB_texture_buffer_object_rgb32 extension", theGlContext);
1342 else if (!theGlContext->arbFBOBlit)
1344 return safeFailBack ("Ray-tracing requires EXT_framebuffer_blit extension", theGlContext);
1347 myRaytraceParameters.NbBounces = myRenderParams.RaytracingDepth;
1349 TCollection_AsciiString aFolder = Graphic3d_ShaderProgram::ShadersFolder();
1351 if (aFolder.IsEmpty())
1353 return safeFailBack ("Failed to locate shaders directory", theGlContext);
1356 if (myIsRaytraceDataValid)
1358 myRaytraceParameters.StackSize = Max (THE_DEFAULT_STACK_SIZE,
1359 myRaytraceGeometry.HighLevelTreeDepth() + myRaytraceGeometry.BottomLevelTreeDepth());
1362 TCollection_AsciiString aPrefixString = generateShaderPrefix (theGlContext);
1364 #ifdef RAY_TRACE_PRINT_INFO
1365 std::cout << "GLSL prefix string:" << std::endl << aPrefixString << std::endl;
1368 ShaderSource aBasicVertShaderSrc;
1370 TCollection_AsciiString aFiles[] = { aFolder + "/RaytraceBase.vs", "" };
1371 if (!aBasicVertShaderSrc.Load (aFiles))
1373 return safeFailBack (aBasicVertShaderSrc.ErrorDescription(), theGlContext);
1378 TCollection_AsciiString aFiles[] = { aFolder + "/RaytraceBase.fs",
1379 aFolder + "/PathtraceBase.fs",
1380 aFolder + "/RaytraceRender.fs",
1382 if (!myRaytraceShaderSource.Load (aFiles, aPrefixString))
1384 return safeFailBack (myRaytraceShaderSource.ErrorDescription(), theGlContext);
1387 Handle(OpenGl_ShaderObject) aBasicVertShader = initShader (GL_VERTEX_SHADER, aBasicVertShaderSrc, theGlContext);
1388 if (aBasicVertShader.IsNull())
1390 return safeFailBack ("Failed to initialize ray-trace vertex shader", theGlContext);
1393 myRaytraceShader = initShader (GL_FRAGMENT_SHADER, myRaytraceShaderSource, theGlContext);
1394 if (myRaytraceShader.IsNull())
1396 aBasicVertShader->Release (theGlContext.operator->());
1397 return safeFailBack ("Failed to initialize ray-trace fragment shader", theGlContext);
1400 myRaytraceProgram = initProgram (theGlContext, aBasicVertShader, myRaytraceShader);
1401 if (myRaytraceProgram.IsNull())
1403 return safeFailBack ("Failed to initialize ray-trace shader program", theGlContext);
1408 TCollection_AsciiString aFiles[] = { aFolder + "/RaytraceBase.fs",
1409 aFolder + "/RaytraceSmooth.fs",
1411 if (!myPostFSAAShaderSource.Load (aFiles, aPrefixString))
1413 return safeFailBack (myPostFSAAShaderSource.ErrorDescription(), theGlContext);
1416 Handle(OpenGl_ShaderObject) aBasicVertShader = initShader (GL_VERTEX_SHADER, aBasicVertShaderSrc, theGlContext);
1417 if (aBasicVertShader.IsNull())
1419 return safeFailBack ("Failed to initialize FSAA vertex shader", theGlContext);
1422 myPostFSAAShader = initShader (GL_FRAGMENT_SHADER, myPostFSAAShaderSource, theGlContext);
1423 if (myPostFSAAShader.IsNull())
1425 aBasicVertShader->Release (theGlContext.operator->());
1426 return safeFailBack ("Failed to initialize FSAA fragment shader", theGlContext);
1429 myPostFSAAProgram = initProgram (theGlContext, aBasicVertShader, myPostFSAAShader);
1430 if (myPostFSAAProgram.IsNull())
1432 return safeFailBack ("Failed to initialize FSAA shader program", theGlContext);
1437 ShaderSource aDispShaderSrc;
1438 TCollection_AsciiString aFiles[] = { aFolder + "/Display.fs", "" };
1439 if (!aDispShaderSrc.Load (aFiles, aPrefixString))
1441 return safeFailBack (aDispShaderSrc.ErrorDescription(), theGlContext);
1444 Handle(OpenGl_ShaderObject) aBasicVertShader = initShader (GL_VERTEX_SHADER, aBasicVertShaderSrc, theGlContext);
1445 if (aBasicVertShader.IsNull())
1447 return safeFailBack ("Failed to set vertex shader source", theGlContext);
1450 Handle(OpenGl_ShaderObject) aDisplayShader = initShader (GL_FRAGMENT_SHADER, aDispShaderSrc, theGlContext);
1451 if (aDisplayShader.IsNull())
1453 aBasicVertShader->Release (theGlContext.operator->());
1454 return safeFailBack ("Failed to set display fragment shader source", theGlContext);
1457 myOutImageProgram = initProgram (theGlContext, aBasicVertShader, aDisplayShader);
1458 if (myOutImageProgram.IsNull())
1460 return safeFailBack ("Failed to initialize output shader program", theGlContext);
1465 if (myRaytraceInitStatus == OpenGl_RT_NONE || aToRebuildShaders)
1467 for (Standard_Integer anIndex = 0; anIndex < 2; ++anIndex)
1469 Handle(OpenGl_ShaderProgram)& aShaderProgram =
1470 (anIndex == 0) ? myRaytraceProgram : myPostFSAAProgram;
1472 theGlContext->BindProgram (aShaderProgram);
1474 aShaderProgram->SetSampler (theGlContext,
1475 "uSceneMinPointTexture", OpenGl_RT_SceneMinPointTexture);
1476 aShaderProgram->SetSampler (theGlContext,
1477 "uSceneMaxPointTexture", OpenGl_RT_SceneMaxPointTexture);
1478 aShaderProgram->SetSampler (theGlContext,
1479 "uSceneNodeInfoTexture", OpenGl_RT_SceneNodeInfoTexture);
1480 aShaderProgram->SetSampler (theGlContext,
1481 "uGeometryVertexTexture", OpenGl_RT_GeometryVertexTexture);
1482 aShaderProgram->SetSampler (theGlContext,
1483 "uGeometryNormalTexture", OpenGl_RT_GeometryNormalTexture);
1484 aShaderProgram->SetSampler (theGlContext,
1485 "uGeometryTexCrdTexture", OpenGl_RT_GeometryTexCrdTexture);
1486 aShaderProgram->SetSampler (theGlContext,
1487 "uGeometryTriangTexture", OpenGl_RT_GeometryTriangTexture);
1488 aShaderProgram->SetSampler (theGlContext,
1489 "uSceneTransformTexture", OpenGl_RT_SceneTransformTexture);
1490 aShaderProgram->SetSampler (theGlContext,
1491 "uEnvironmentMapTexture", OpenGl_RT_EnvironmentMapTexture);
1492 aShaderProgram->SetSampler (theGlContext,
1493 "uRaytraceMaterialTexture", OpenGl_RT_RaytraceMaterialTexture);
1494 aShaderProgram->SetSampler (theGlContext,
1495 "uRaytraceLightSrcTexture", OpenGl_RT_RaytraceLightSrcTexture);
1497 aShaderProgram->SetSampler (theGlContext,
1498 "uOpenGlColorTexture", OpenGl_RT_OpenGlColorTexture);
1499 aShaderProgram->SetSampler (theGlContext,
1500 "uOpenGlDepthTexture", OpenGl_RT_OpenGlDepthTexture);
1504 aShaderProgram->SetSampler (theGlContext,
1505 "uFSAAInputTexture", OpenGl_RT_FsaaInputTexture);
1509 aShaderProgram->SetSampler (theGlContext,
1510 "uAccumTexture", OpenGl_RT_PrevAccumTexture);
1513 myUniformLocations[anIndex][OpenGl_RT_aPosition] =
1514 aShaderProgram->GetAttributeLocation (theGlContext, "occVertex");
1516 myUniformLocations[anIndex][OpenGl_RT_uOriginLB] =
1517 aShaderProgram->GetUniformLocation (theGlContext, "uOriginLB");
1518 myUniformLocations[anIndex][OpenGl_RT_uOriginRB] =
1519 aShaderProgram->GetUniformLocation (theGlContext, "uOriginRB");
1520 myUniformLocations[anIndex][OpenGl_RT_uOriginLT] =
1521 aShaderProgram->GetUniformLocation (theGlContext, "uOriginLT");
1522 myUniformLocations[anIndex][OpenGl_RT_uOriginRT] =
1523 aShaderProgram->GetUniformLocation (theGlContext, "uOriginRT");
1524 myUniformLocations[anIndex][OpenGl_RT_uDirectLB] =
1525 aShaderProgram->GetUniformLocation (theGlContext, "uDirectLB");
1526 myUniformLocations[anIndex][OpenGl_RT_uDirectRB] =
1527 aShaderProgram->GetUniformLocation (theGlContext, "uDirectRB");
1528 myUniformLocations[anIndex][OpenGl_RT_uDirectLT] =
1529 aShaderProgram->GetUniformLocation (theGlContext, "uDirectLT");
1530 myUniformLocations[anIndex][OpenGl_RT_uDirectRT] =
1531 aShaderProgram->GetUniformLocation (theGlContext, "uDirectRT");
1532 myUniformLocations[anIndex][OpenGl_RT_uUnviewMat] =
1533 aShaderProgram->GetUniformLocation (theGlContext, "uUnviewMat");
1535 myUniformLocations[anIndex][OpenGl_RT_uSceneRad] =
1536 aShaderProgram->GetUniformLocation (theGlContext, "uSceneRadius");
1537 myUniformLocations[anIndex][OpenGl_RT_uSceneEps] =
1538 aShaderProgram->GetUniformLocation (theGlContext, "uSceneEpsilon");
1539 myUniformLocations[anIndex][OpenGl_RT_uLightCount] =
1540 aShaderProgram->GetUniformLocation (theGlContext, "uLightCount");
1541 myUniformLocations[anIndex][OpenGl_RT_uLightAmbnt] =
1542 aShaderProgram->GetUniformLocation (theGlContext, "uGlobalAmbient");
1544 myUniformLocations[anIndex][OpenGl_RT_uOffsetX] =
1545 aShaderProgram->GetUniformLocation (theGlContext, "uOffsetX");
1546 myUniformLocations[anIndex][OpenGl_RT_uOffsetY] =
1547 aShaderProgram->GetUniformLocation (theGlContext, "uOffsetY");
1548 myUniformLocations[anIndex][OpenGl_RT_uSamples] =
1549 aShaderProgram->GetUniformLocation (theGlContext, "uSamples");
1551 myUniformLocations[anIndex][OpenGl_RT_uTexSamplersArray] =
1552 aShaderProgram->GetUniformLocation (theGlContext, "uTextureSamplers");
1554 myUniformLocations[anIndex][OpenGl_RT_uShadowsEnabled] =
1555 aShaderProgram->GetUniformLocation (theGlContext, "uShadowsEnabled");
1556 myUniformLocations[anIndex][OpenGl_RT_uReflectEnabled] =
1557 aShaderProgram->GetUniformLocation (theGlContext, "uReflectEnabled");
1558 myUniformLocations[anIndex][OpenGl_RT_uSphereMapEnabled] =
1559 aShaderProgram->GetUniformLocation (theGlContext, "uSphereMapEnabled");
1560 myUniformLocations[anIndex][OpenGl_RT_uSphereMapForBack] =
1561 aShaderProgram->GetUniformLocation (theGlContext, "uSphereMapForBack");
1562 myUniformLocations[anIndex][OpenGl_RT_uBlockedRngEnabled] =
1563 aShaderProgram->GetUniformLocation (theGlContext, "uBlockedRngEnabled");
1565 myUniformLocations[anIndex][OpenGl_RT_uSampleWeight] =
1566 aShaderProgram->GetUniformLocation (theGlContext, "uSampleWeight");
1567 myUniformLocations[anIndex][OpenGl_RT_uFrameRndSeed] =
1568 aShaderProgram->GetUniformLocation (theGlContext, "uFrameRndSeed");
1570 myUniformLocations[anIndex][OpenGl_RT_uBackColorTop] =
1571 aShaderProgram->GetUniformLocation (theGlContext, "uBackColorTop");
1572 myUniformLocations[anIndex][OpenGl_RT_uBackColorBot] =
1573 aShaderProgram->GetUniformLocation (theGlContext, "uBackColorBot");
1576 theGlContext->BindProgram (myOutImageProgram);
1578 myOutImageProgram->SetSampler (theGlContext,
1579 "uInputTexture", OpenGl_RT_PrevAccumTexture);
1581 theGlContext->BindProgram (NULL);
1584 if (myRaytraceInitStatus != OpenGl_RT_NONE)
1586 return myRaytraceInitStatus == OpenGl_RT_INIT;
1589 if (myRaytraceFBO1.IsNull())
1591 myRaytraceFBO1 = new OpenGl_FrameBuffer (GL_RGBA32F);
1594 if (myRaytraceFBO2.IsNull())
1596 myRaytraceFBO2 = new OpenGl_FrameBuffer (GL_RGBA32F);
1599 const GLfloat aVertices[] = { -1.f, -1.f, 0.f,
1606 myRaytraceScreenQuad.Init (theGlContext, 3, 6, aVertices);
1608 myRaytraceInitStatus = OpenGl_RT_INIT; // initialized in normal way
1610 return Standard_True;
1613 // =======================================================================
1614 // function : nullifyResource
1616 // =======================================================================
1617 inline void nullifyResource (const Handle(OpenGl_Context)& theGlContext,
1618 Handle(OpenGl_Resource)& theResource)
1620 if (!theResource.IsNull())
1622 theResource->Release (theGlContext.operator->());
1623 theResource.Nullify();
1627 // =======================================================================
1628 // function : releaseRaytraceResources
1629 // purpose : Releases OpenGL/GLSL shader programs
1630 // =======================================================================
1631 void OpenGl_View::releaseRaytraceResources (const Handle(OpenGl_Context)& theGlContext)
1633 nullifyResource (theGlContext, myOpenGlFBO);
1634 nullifyResource (theGlContext, myRaytraceFBO1);
1635 nullifyResource (theGlContext, myRaytraceFBO2);
1637 nullifyResource (theGlContext, myRaytraceShader);
1638 nullifyResource (theGlContext, myPostFSAAShader);
1640 nullifyResource (theGlContext, myRaytraceProgram);
1641 nullifyResource (theGlContext, myPostFSAAProgram);
1642 nullifyResource (theGlContext, myOutImageProgram);
1644 nullifyResource (theGlContext, mySceneNodeInfoTexture);
1645 nullifyResource (theGlContext, mySceneMinPointTexture);
1646 nullifyResource (theGlContext, mySceneMaxPointTexture);
1648 nullifyResource (theGlContext, myGeometryVertexTexture);
1649 nullifyResource (theGlContext, myGeometryNormalTexture);
1650 nullifyResource (theGlContext, myGeometryTexCrdTexture);
1651 nullifyResource (theGlContext, myGeometryTriangTexture);
1652 nullifyResource (theGlContext, mySceneTransformTexture);
1654 nullifyResource (theGlContext, myRaytraceLightSrcTexture);
1655 nullifyResource (theGlContext, myRaytraceMaterialTexture);
1657 myRaytraceGeometry.ReleaseResources (theGlContext);
1659 if (myRaytraceScreenQuad.IsValid())
1660 myRaytraceScreenQuad.Release (theGlContext.operator->());
1663 // =======================================================================
1664 // function : resizeRaytraceBuffers
1665 // purpose : Resizes OpenGL frame buffers
1666 // =======================================================================
1667 Standard_Boolean OpenGl_View::resizeRaytraceBuffers (const Standard_Integer theSizeX,
1668 const Standard_Integer theSizeY,
1669 const Handle(OpenGl_Context)& theGlContext)
1671 if (myRaytraceFBO1->GetVPSizeX() != theSizeX
1672 || myRaytraceFBO1->GetVPSizeY() != theSizeY)
1674 myRaytraceFBO1->Init (theGlContext, theSizeX, theSizeY);
1675 myRaytraceFBO2->Init (theGlContext, theSizeX, theSizeY);
1678 return Standard_True;
1681 // =======================================================================
1682 // function : updateCamera
1683 // purpose : Generates viewing rays for corners of screen quad
1684 // =======================================================================
1685 void OpenGl_View::updateCamera (const OpenGl_Mat4& theOrientation,
1686 const OpenGl_Mat4& theViewMapping,
1687 OpenGl_Vec3* theOrigins,
1688 OpenGl_Vec3* theDirects,
1689 OpenGl_Mat4& theUnview)
1691 // compute inverse model-view-projection matrix
1692 (theViewMapping * theOrientation).Inverted (theUnview);
1694 Standard_Integer aOriginIndex = 0;
1695 Standard_Integer aDirectIndex = 0;
1697 for (Standard_Integer aY = -1; aY <= 1; aY += 2)
1699 for (Standard_Integer aX = -1; aX <= 1; aX += 2)
1701 OpenGl_Vec4 aOrigin (GLfloat(aX),
1706 aOrigin = theUnview * aOrigin;
1708 aOrigin.x() = aOrigin.x() / aOrigin.w();
1709 aOrigin.y() = aOrigin.y() / aOrigin.w();
1710 aOrigin.z() = aOrigin.z() / aOrigin.w();
1712 OpenGl_Vec4 aDirect (GLfloat(aX),
1717 aDirect = theUnview * aDirect;
1719 aDirect.x() = aDirect.x() / aDirect.w();
1720 aDirect.y() = aDirect.y() / aDirect.w();
1721 aDirect.z() = aDirect.z() / aDirect.w();
1723 aDirect = aDirect - aOrigin;
1725 GLdouble aInvLen = 1.0 / sqrt (aDirect.x() * aDirect.x() +
1726 aDirect.y() * aDirect.y() +
1727 aDirect.z() * aDirect.z());
1729 theOrigins[aOriginIndex++] = OpenGl_Vec3 (static_cast<GLfloat> (aOrigin.x()),
1730 static_cast<GLfloat> (aOrigin.y()),
1731 static_cast<GLfloat> (aOrigin.z()));
1733 theDirects[aDirectIndex++] = OpenGl_Vec3 (static_cast<GLfloat> (aDirect.x() * aInvLen),
1734 static_cast<GLfloat> (aDirect.y() * aInvLen),
1735 static_cast<GLfloat> (aDirect.z() * aInvLen));
1740 // =======================================================================
1741 // function : uploadRaytraceData
1742 // purpose : Uploads ray-trace data to the GPU
1743 // =======================================================================
1744 Standard_Boolean OpenGl_View::uploadRaytraceData (const Handle(OpenGl_Context)& theGlContext)
1746 if (!theGlContext->IsGlGreaterEqual (3, 1))
1748 #ifdef RAY_TRACE_PRINT_INFO
1749 std::cout << "Error: OpenGL version is less than 3.1" << std::endl;
1751 return Standard_False;
1754 myAccumFrames = 0; // accumulation should be restarted
1756 /////////////////////////////////////////////////////////////////////////////
1757 // Prepare OpenGL textures
1759 if (theGlContext->arbTexBindless != NULL)
1761 // If OpenGL driver supports bindless textures we need
1762 // to get unique 64- bit handles for using on the GPU
1763 if (!myRaytraceGeometry.UpdateTextureHandles (theGlContext))
1765 #ifdef RAY_TRACE_PRINT_INFO
1766 std::cout << "Error: Failed to get OpenGL texture handles" << std::endl;
1768 return Standard_False;
1772 /////////////////////////////////////////////////////////////////////////////
1773 // Create OpenGL BVH buffers
1775 if (mySceneNodeInfoTexture.IsNull()) // create scene BVH buffers
1777 mySceneNodeInfoTexture = new OpenGl_TextureBufferArb;
1778 mySceneMinPointTexture = new OpenGl_TextureBufferArb;
1779 mySceneMaxPointTexture = new OpenGl_TextureBufferArb;
1780 mySceneTransformTexture = new OpenGl_TextureBufferArb;
1782 if (!mySceneNodeInfoTexture->Create (theGlContext)
1783 || !mySceneMinPointTexture->Create (theGlContext)
1784 || !mySceneMaxPointTexture->Create (theGlContext)
1785 || !mySceneTransformTexture->Create (theGlContext))
1787 #ifdef RAY_TRACE_PRINT_INFO
1788 std::cout << "Error: Failed to create scene BVH buffers" << std::endl;
1790 return Standard_False;
1794 if (myGeometryVertexTexture.IsNull()) // create geometry buffers
1796 myGeometryVertexTexture = new OpenGl_TextureBufferArb;
1797 myGeometryNormalTexture = new OpenGl_TextureBufferArb;
1798 myGeometryTexCrdTexture = new OpenGl_TextureBufferArb;
1799 myGeometryTriangTexture = new OpenGl_TextureBufferArb;
1801 if (!myGeometryVertexTexture->Create (theGlContext)
1802 || !myGeometryNormalTexture->Create (theGlContext)
1803 || !myGeometryTexCrdTexture->Create (theGlContext)
1804 || !myGeometryTriangTexture->Create (theGlContext))
1806 #ifdef RAY_TRACE_PRINT_INFO
1807 std::cout << "Error: Failed to create buffers for triangulation data" << std::endl;
1809 return Standard_False;
1813 if (myRaytraceMaterialTexture.IsNull()) // create material buffer
1815 myRaytraceMaterialTexture = new OpenGl_TextureBufferArb;
1817 if (!myRaytraceMaterialTexture->Create (theGlContext))
1819 #ifdef RAY_TRACE_PRINT_INFO
1820 std::cout << "Error: Failed to create buffers for material data" << std::endl;
1822 return Standard_False;
1826 /////////////////////////////////////////////////////////////////////////////
1827 // Write transform buffer
1829 BVH_Mat4f* aNodeTransforms = new BVH_Mat4f[myRaytraceGeometry.Size()];
1831 bool aResult = true;
1833 for (Standard_Integer anElemIndex = 0; anElemIndex < myRaytraceGeometry.Size(); ++anElemIndex)
1835 OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
1836 myRaytraceGeometry.Objects().ChangeValue (anElemIndex).operator->());
1838 const BVH_Transform<Standard_ShortReal, 4>* aTransform =
1839 dynamic_cast<const BVH_Transform<Standard_ShortReal, 4>* > (aTriangleSet->Properties().operator->());
1841 Standard_ASSERT_RETURN (aTransform != NULL,
1842 "OpenGl_TriangleSet does not contain transform", Standard_False);
1844 aNodeTransforms[anElemIndex] = aTransform->Inversed();
1847 aResult &= mySceneTransformTexture->Init (theGlContext, 4,
1848 myRaytraceGeometry.Size() * 4, reinterpret_cast<const GLfloat*> (aNodeTransforms));
1850 delete [] aNodeTransforms;
1852 /////////////////////////////////////////////////////////////////////////////
1853 // Write geometry and bottom-level BVH buffers
1855 Standard_Size aTotalVerticesNb = 0;
1856 Standard_Size aTotalElementsNb = 0;
1857 Standard_Size aTotalBVHNodesNb = 0;
1859 for (Standard_Integer anElemIndex = 0; anElemIndex < myRaytraceGeometry.Size(); ++anElemIndex)
1861 OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
1862 myRaytraceGeometry.Objects().ChangeValue (anElemIndex).operator->());
1864 Standard_ASSERT_RETURN (aTriangleSet != NULL,
1865 "Error: Failed to get triangulation of OpenGL element", Standard_False);
1867 aTotalVerticesNb += aTriangleSet->Vertices.size();
1868 aTotalElementsNb += aTriangleSet->Elements.size();
1870 Standard_ASSERT_RETURN (!aTriangleSet->BVH().IsNull(),
1871 "Error: Failed to get bottom-level BVH of OpenGL element", Standard_False);
1873 aTotalBVHNodesNb += aTriangleSet->BVH()->NodeInfoBuffer().size();
1876 aTotalBVHNodesNb += myRaytraceGeometry.BVH()->NodeInfoBuffer().size();
1878 if (aTotalBVHNodesNb != 0)
1880 aResult &= mySceneNodeInfoTexture->Init (
1881 theGlContext, 4, GLsizei (aTotalBVHNodesNb), static_cast<const GLuint*> (NULL));
1882 aResult &= mySceneMinPointTexture->Init (
1883 theGlContext, 3, GLsizei (aTotalBVHNodesNb), static_cast<const GLfloat*> (NULL));
1884 aResult &= mySceneMaxPointTexture->Init (
1885 theGlContext, 3, GLsizei (aTotalBVHNodesNb), static_cast<const GLfloat*> (NULL));
1890 #ifdef RAY_TRACE_PRINT_INFO
1891 std::cout << "Error: Failed to upload buffers for bottom-level scene BVH" << std::endl;
1893 return Standard_False;
1896 if (aTotalElementsNb != 0)
1898 aResult &= myGeometryTriangTexture->Init (
1899 theGlContext, 4, GLsizei (aTotalElementsNb), static_cast<const GLuint*> (NULL));
1902 if (aTotalVerticesNb != 0)
1904 aResult &= myGeometryVertexTexture->Init (
1905 theGlContext, 3, GLsizei (aTotalVerticesNb), static_cast<const GLfloat*> (NULL));
1906 aResult &= myGeometryNormalTexture->Init (
1907 theGlContext, 3, GLsizei (aTotalVerticesNb), static_cast<const GLfloat*> (NULL));
1908 aResult &= myGeometryTexCrdTexture->Init (
1909 theGlContext, 2, GLsizei (aTotalVerticesNb), static_cast<const GLfloat*> (NULL));
1914 #ifdef RAY_TRACE_PRINT_INFO
1915 std::cout << "Error: Failed to upload buffers for scene geometry" << std::endl;
1917 return Standard_False;
1920 const NCollection_Handle<BVH_Tree<Standard_ShortReal, 3> >& aBVH = myRaytraceGeometry.BVH();
1922 if (aBVH->Length() > 0)
1924 aResult &= mySceneNodeInfoTexture->SubData (theGlContext, 0, aBVH->Length(),
1925 reinterpret_cast<const GLuint*> (&aBVH->NodeInfoBuffer().front()));
1926 aResult &= mySceneMinPointTexture->SubData (theGlContext, 0, aBVH->Length(),
1927 reinterpret_cast<const GLfloat*> (&aBVH->MinPointBuffer().front()));
1928 aResult &= mySceneMaxPointTexture->SubData (theGlContext, 0, aBVH->Length(),
1929 reinterpret_cast<const GLfloat*> (&aBVH->MaxPointBuffer().front()));
1932 for (Standard_Integer aNodeIdx = 0; aNodeIdx < aBVH->Length(); ++aNodeIdx)
1934 if (!aBVH->IsOuter (aNodeIdx))
1937 OpenGl_TriangleSet* aTriangleSet = myRaytraceGeometry.TriangleSet (aNodeIdx);
1939 Standard_ASSERT_RETURN (aTriangleSet != NULL,
1940 "Error: Failed to get triangulation of OpenGL element", Standard_False);
1942 Standard_Integer aBVHOffset = myRaytraceGeometry.AccelerationOffset (aNodeIdx);
1944 Standard_ASSERT_RETURN (aBVHOffset != OpenGl_RaytraceGeometry::INVALID_OFFSET,
1945 "Error: Failed to get offset for bottom-level BVH", Standard_False);
1947 const Standard_Integer aBvhBuffersSize = aTriangleSet->BVH()->Length();
1949 if (aBvhBuffersSize != 0)
1951 aResult &= mySceneNodeInfoTexture->SubData (theGlContext, aBVHOffset, aBvhBuffersSize,
1952 reinterpret_cast<const GLuint*> (&aTriangleSet->BVH()->NodeInfoBuffer().front()));
1953 aResult &= mySceneMinPointTexture->SubData (theGlContext, aBVHOffset, aBvhBuffersSize,
1954 reinterpret_cast<const GLfloat*> (&aTriangleSet->BVH()->MinPointBuffer().front()));
1955 aResult &= mySceneMaxPointTexture->SubData (theGlContext, aBVHOffset, aBvhBuffersSize,
1956 reinterpret_cast<const GLfloat*> (&aTriangleSet->BVH()->MaxPointBuffer().front()));
1960 #ifdef RAY_TRACE_PRINT_INFO
1961 std::cout << "Error: Failed to upload buffers for bottom-level scene BVHs" << std::endl;
1963 return Standard_False;
1967 const Standard_Integer aVerticesOffset = myRaytraceGeometry.VerticesOffset (aNodeIdx);
1969 Standard_ASSERT_RETURN (aVerticesOffset != OpenGl_RaytraceGeometry::INVALID_OFFSET,
1970 "Error: Failed to get offset for triangulation vertices of OpenGL element", Standard_False);
1972 if (!aTriangleSet->Vertices.empty())
1974 aResult &= myGeometryNormalTexture->SubData (theGlContext, aVerticesOffset,
1975 GLsizei (aTriangleSet->Normals.size()), reinterpret_cast<const GLfloat*> (&aTriangleSet->Normals.front()));
1976 aResult &= myGeometryTexCrdTexture->SubData (theGlContext, aVerticesOffset,
1977 GLsizei (aTriangleSet->TexCrds.size()), reinterpret_cast<const GLfloat*> (&aTriangleSet->TexCrds.front()));
1978 aResult &= myGeometryVertexTexture->SubData (theGlContext, aVerticesOffset,
1979 GLsizei (aTriangleSet->Vertices.size()), reinterpret_cast<const GLfloat*> (&aTriangleSet->Vertices.front()));
1982 const Standard_Integer anElementsOffset = myRaytraceGeometry.ElementsOffset (aNodeIdx);
1984 Standard_ASSERT_RETURN (anElementsOffset != OpenGl_RaytraceGeometry::INVALID_OFFSET,
1985 "Error: Failed to get offset for triangulation elements of OpenGL element", Standard_False);
1987 if (!aTriangleSet->Elements.empty())
1989 aResult &= myGeometryTriangTexture->SubData (theGlContext, anElementsOffset, GLsizei (aTriangleSet->Elements.size()),
1990 reinterpret_cast<const GLuint*> (&aTriangleSet->Elements.front()));
1995 #ifdef RAY_TRACE_PRINT_INFO
1996 std::cout << "Error: Failed to upload triangulation buffers for OpenGL element" << std::endl;
1998 return Standard_False;
2002 /////////////////////////////////////////////////////////////////////////////
2003 // Write material buffer
2005 if (myRaytraceGeometry.Materials.size() != 0)
2007 aResult &= myRaytraceMaterialTexture->Init (theGlContext, 4,
2008 GLsizei (myRaytraceGeometry.Materials.size() * 18), myRaytraceGeometry.Materials.front().Packed());
2012 #ifdef RAY_TRACE_PRINT_INFO
2013 std::cout << "Error: Failed to upload material buffer" << std::endl;
2015 return Standard_False;
2019 myIsRaytraceDataValid = myRaytraceGeometry.Objects().Size() != 0;
2021 #ifdef RAY_TRACE_PRINT_INFO
2023 Standard_ShortReal aMemUsed = 0.f;
2025 for (Standard_Integer anElemIdx = 0; anElemIdx < myRaytraceGeometry.Size(); ++anElemIdx)
2027 OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
2028 myRaytraceGeometry.Objects().ChangeValue (anElemIdx).operator->());
2030 aMemUsed += static_cast<Standard_ShortReal> (
2031 aTriangleSet->Vertices.size() * sizeof (BVH_Vec3f));
2032 aMemUsed += static_cast<Standard_ShortReal> (
2033 aTriangleSet->Normals.size() * sizeof (BVH_Vec3f));
2034 aMemUsed += static_cast<Standard_ShortReal> (
2035 aTriangleSet->TexCrds.size() * sizeof (BVH_Vec2f));
2036 aMemUsed += static_cast<Standard_ShortReal> (
2037 aTriangleSet->Elements.size() * sizeof (BVH_Vec4i));
2039 aMemUsed += static_cast<Standard_ShortReal> (
2040 aTriangleSet->BVH()->NodeInfoBuffer().size() * sizeof (BVH_Vec4i));
2041 aMemUsed += static_cast<Standard_ShortReal> (
2042 aTriangleSet->BVH()->MinPointBuffer().size() * sizeof (BVH_Vec3f));
2043 aMemUsed += static_cast<Standard_ShortReal> (
2044 aTriangleSet->BVH()->MaxPointBuffer().size() * sizeof (BVH_Vec3f));
2047 aMemUsed += static_cast<Standard_ShortReal> (
2048 myRaytraceGeometry.BVH()->NodeInfoBuffer().size() * sizeof (BVH_Vec4i));
2049 aMemUsed += static_cast<Standard_ShortReal> (
2050 myRaytraceGeometry.BVH()->MinPointBuffer().size() * sizeof (BVH_Vec3f));
2051 aMemUsed += static_cast<Standard_ShortReal> (
2052 myRaytraceGeometry.BVH()->MaxPointBuffer().size() * sizeof (BVH_Vec3f));
2054 std::cout << "GPU Memory Used (MB): ~" << aMemUsed / 1048576 << std::endl;
2061 // =======================================================================
2062 // function : updateRaytraceLightSources
2063 // purpose : Updates 3D scene light sources for ray-tracing
2064 // =======================================================================
2065 Standard_Boolean OpenGl_View::updateRaytraceLightSources (const OpenGl_Mat4& theInvModelView, const Handle(OpenGl_Context)& theGlContext)
2067 myRaytraceGeometry.Sources.clear();
2069 myRaytraceGeometry.Ambient = BVH_Vec4f (0.0f, 0.0f, 0.0f, 0.0f);
2071 OpenGl_ListOfLight::Iterator aLightIter (myShadingModel == Graphic3d_TOSM_NONE ? OpenGl_NoShadingLight() : myLights);
2072 for (; aLightIter.More(); aLightIter.Next())
2074 const OpenGl_Light& aLight = aLightIter.Value();
2076 if (aLight.Type == Graphic3d_TOLS_AMBIENT)
2078 myRaytraceGeometry.Ambient += BVH_Vec4f (aLight.Color.r() * aLight.Intensity,
2079 aLight.Color.g() * aLight.Intensity,
2080 aLight.Color.b() * aLight.Intensity,
2085 BVH_Vec4f aDiffuse (aLight.Color.r() * aLight.Intensity,
2086 aLight.Color.g() * aLight.Intensity,
2087 aLight.Color.b() * aLight.Intensity,
2090 BVH_Vec4f aPosition (-aLight.Direction.x(),
2091 -aLight.Direction.y(),
2092 -aLight.Direction.z(),
2095 if (aLight.Type != Graphic3d_TOLS_DIRECTIONAL)
2097 aPosition = BVH_Vec4f (aLight.Position.x(),
2098 aLight.Position.y(),
2099 aLight.Position.z(),
2102 // store smoothing radius in w-component
2103 aDiffuse.w() = Max (aLight.Smoothness, 0.f);
2107 // store cosine of smoothing angle in w-component
2108 aDiffuse.w() = cosf (Min (Max (aLight.Smoothness, 0.f), static_cast<Standard_ShortReal> (M_PI / 2.0)));
2111 if (aLight.IsHeadlight)
2113 aPosition = theInvModelView * aPosition;
2116 myRaytraceGeometry.Sources.push_back (OpenGl_RaytraceLight (aDiffuse, aPosition));
2119 if (myRaytraceLightSrcTexture.IsNull()) // create light source buffer
2121 myRaytraceLightSrcTexture = new OpenGl_TextureBufferArb;
2123 if (!myRaytraceLightSrcTexture->Create (theGlContext))
2125 #ifdef RAY_TRACE_PRINT_INFO
2126 std::cout << "Error: Failed to create light source buffer" << std::endl;
2128 return Standard_False;
2132 if (myRaytraceGeometry.Sources.size() != 0)
2134 const GLfloat* aDataPtr = myRaytraceGeometry.Sources.front().Packed();
2135 if (!myRaytraceLightSrcTexture->Init (theGlContext, 4, GLsizei (myRaytraceGeometry.Sources.size() * 2), aDataPtr))
2137 #ifdef RAY_TRACE_PRINT_INFO
2138 std::cout << "Error: Failed to upload light source buffer" << std::endl;
2140 return Standard_False;
2144 return Standard_True;
2147 // =======================================================================
2148 // function : updateRaytraceEnvironmentMap
2149 // purpose : Updates environment map for ray-tracing
2150 // =======================================================================
2151 Standard_Boolean OpenGl_View::updateRaytraceEnvironmentMap (const Handle(OpenGl_Context)& theGlContext)
2153 Standard_Boolean aResult = Standard_True;
2155 if (!myToUpdateEnvironmentMap)
2160 for (Standard_Integer anIdx = 0; anIdx < 2; ++anIdx)
2162 const Handle(OpenGl_ShaderProgram)& aProgram =
2163 anIdx == 0 ? myRaytraceProgram : myPostFSAAProgram;
2165 if (!aProgram.IsNull())
2167 aResult &= theGlContext->BindProgram (aProgram);
2169 if (!myTextureEnv.IsNull() && mySurfaceDetail != Graphic3d_TOD_NONE)
2171 myTextureEnv->Bind (theGlContext,
2172 GL_TEXTURE0 + OpenGl_RT_EnvironmentMapTexture);
2174 aResult &= aProgram->SetUniform (theGlContext,
2175 myUniformLocations[anIdx][OpenGl_RT_uSphereMapEnabled], 1);
2179 aResult &= aProgram->SetUniform (theGlContext,
2180 myUniformLocations[anIdx][OpenGl_RT_uSphereMapEnabled], 0);
2185 myToUpdateEnvironmentMap = Standard_False;
2187 theGlContext->BindProgram (NULL);
2192 // =======================================================================
2193 // function : setUniformState
2194 // purpose : Sets uniform state for the given ray-tracing shader program
2195 // =======================================================================
2196 Standard_Boolean OpenGl_View::setUniformState (const OpenGl_Vec3* theOrigins,
2197 const OpenGl_Vec3* theDirects,
2198 const OpenGl_Mat4& theUnviewMat,
2199 const Standard_Integer theProgramId,
2200 const Handle(OpenGl_Context)& theGlContext)
2202 Handle(OpenGl_ShaderProgram)& theProgram =
2203 theProgramId == 0 ? myRaytraceProgram : myPostFSAAProgram;
2205 if (theProgram.IsNull())
2207 return Standard_False;
2210 const Standard_Integer aLightSourceBufferSize =
2211 static_cast<Standard_Integer> (myRaytraceGeometry.Sources.size());
2214 theProgram->SetUniform (theGlContext,
2215 myUniformLocations[theProgramId][OpenGl_RT_uOriginLB], theOrigins[0]);
2216 theProgram->SetUniform (theGlContext,
2217 myUniformLocations[theProgramId][OpenGl_RT_uOriginRB], theOrigins[1]);
2218 theProgram->SetUniform (theGlContext,
2219 myUniformLocations[theProgramId][OpenGl_RT_uOriginLT], theOrigins[2]);
2220 theProgram->SetUniform (theGlContext,
2221 myUniformLocations[theProgramId][OpenGl_RT_uOriginRT], theOrigins[3]);
2222 theProgram->SetUniform (theGlContext,
2223 myUniformLocations[theProgramId][OpenGl_RT_uDirectLB], theDirects[0]);
2224 theProgram->SetUniform (theGlContext,
2225 myUniformLocations[theProgramId][OpenGl_RT_uDirectRB], theDirects[1]);
2226 theProgram->SetUniform (theGlContext,
2227 myUniformLocations[theProgramId][OpenGl_RT_uDirectLT], theDirects[2]);
2228 theProgram->SetUniform (theGlContext,
2229 myUniformLocations[theProgramId][OpenGl_RT_uDirectRT], theDirects[3]);
2230 theProgram->SetUniform (theGlContext,
2231 myUniformLocations[theProgramId][OpenGl_RT_uUnviewMat], theUnviewMat);
2233 // Set scene parameters
2234 theProgram->SetUniform (theGlContext,
2235 myUniformLocations[theProgramId][OpenGl_RT_uSceneRad], myRaytraceSceneRadius);
2236 theProgram->SetUniform (theGlContext,
2237 myUniformLocations[theProgramId][OpenGl_RT_uSceneEps], myRaytraceSceneEpsilon);
2238 theProgram->SetUniform (theGlContext,
2239 myUniformLocations[theProgramId][OpenGl_RT_uLightCount], aLightSourceBufferSize);
2240 theProgram->SetUniform (theGlContext,
2241 myUniformLocations[theProgramId][OpenGl_RT_uLightAmbnt], myRaytraceGeometry.Ambient);
2243 // Set run-time rendering options
2244 theProgram->SetUniform (theGlContext,
2245 myUniformLocations[theProgramId][OpenGl_RT_uShadowsEnabled], myRenderParams.IsShadowEnabled ? 1 : 0);
2246 theProgram->SetUniform (theGlContext,
2247 myUniformLocations[theProgramId][OpenGl_RT_uReflectEnabled], myRenderParams.IsReflectionEnabled ? 1 : 0);
2249 if (myRenderParams.IsGlobalIlluminationEnabled)
2251 theProgram->SetUniform (theGlContext,
2252 myUniformLocations[theProgramId][OpenGl_RT_uBlockedRngEnabled], myRenderParams.CoherentPathTracingMode ? 1 : 0);
2255 // Set array of 64-bit texture handles
2256 if (theGlContext->arbTexBindless != NULL && myRaytraceGeometry.HasTextures())
2258 const std::vector<GLuint64>& aTextures = myRaytraceGeometry.TextureHandles();
2260 theProgram->SetUniform (theGlContext, myUniformLocations[theProgramId][OpenGl_RT_uTexSamplersArray],
2261 static_cast<GLsizei> (aTextures.size()), (OpenGl_Vec2u* )&aTextures.front());
2264 // Set background colors (only gradient background supported)
2265 if (myBgGradientArray != NULL
2266 && myBgGradientArray->IsDefined())
2268 theProgram->SetUniform (theGlContext,
2269 myUniformLocations[theProgramId][OpenGl_RT_uBackColorTop], myBgGradientArray->GradientColor (0));
2270 theProgram->SetUniform (theGlContext,
2271 myUniformLocations[theProgramId][OpenGl_RT_uBackColorBot], myBgGradientArray->GradientColor (1));
2275 const OpenGl_Vec4 aBackColor (myBgColor.rgb[0],
2279 theProgram->SetUniform (theGlContext,
2280 myUniformLocations[theProgramId][OpenGl_RT_uBackColorTop], aBackColor);
2281 theProgram->SetUniform (theGlContext,
2282 myUniformLocations[theProgramId][OpenGl_RT_uBackColorBot], aBackColor);
2285 theProgram->SetUniform (theGlContext,
2286 myUniformLocations[theProgramId][OpenGl_RT_uSphereMapForBack], myRenderParams.UseEnvironmentMapBackground ? 1 : 0);
2288 return Standard_True;
2291 // =======================================================================
2292 // function : bindRaytraceTextures
2293 // purpose : Binds ray-trace textures to corresponding texture units
2294 // =======================================================================
2295 void OpenGl_View::bindRaytraceTextures (const Handle(OpenGl_Context)& theGlContext)
2297 mySceneMinPointTexture->BindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_SceneMinPointTexture);
2298 mySceneMaxPointTexture->BindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_SceneMaxPointTexture);
2299 mySceneNodeInfoTexture->BindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_SceneNodeInfoTexture);
2300 myGeometryVertexTexture->BindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryVertexTexture);
2301 myGeometryNormalTexture->BindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryNormalTexture);
2302 myGeometryTexCrdTexture->BindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryTexCrdTexture);
2303 myGeometryTriangTexture->BindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryTriangTexture);
2304 mySceneTransformTexture->BindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_SceneTransformTexture);
2305 myRaytraceMaterialTexture->BindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_RaytraceMaterialTexture);
2306 myRaytraceLightSrcTexture->BindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_RaytraceLightSrcTexture);
2308 if (!myOpenGlFBO.IsNull())
2310 myOpenGlFBO->ColorTexture()->Bind (theGlContext, GL_TEXTURE0 + OpenGl_RT_OpenGlColorTexture);
2311 myOpenGlFBO->DepthStencilTexture()->Bind (theGlContext, GL_TEXTURE0 + OpenGl_RT_OpenGlDepthTexture);
2315 // =======================================================================
2316 // function : unbindRaytraceTextures
2317 // purpose : Unbinds ray-trace textures from corresponding texture units
2318 // =======================================================================
2319 void OpenGl_View::unbindRaytraceTextures (const Handle(OpenGl_Context)& theGlContext)
2321 mySceneMinPointTexture->UnbindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_SceneMinPointTexture);
2322 mySceneMaxPointTexture->UnbindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_SceneMaxPointTexture);
2323 mySceneNodeInfoTexture->UnbindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_SceneNodeInfoTexture);
2324 myGeometryVertexTexture->UnbindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryVertexTexture);
2325 myGeometryNormalTexture->UnbindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryNormalTexture);
2326 myGeometryTexCrdTexture->UnbindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryTexCrdTexture);
2327 myGeometryTriangTexture->UnbindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryTriangTexture);
2328 mySceneTransformTexture->UnbindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_SceneTransformTexture);
2329 myRaytraceMaterialTexture->UnbindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_RaytraceMaterialTexture);
2330 myRaytraceLightSrcTexture->UnbindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_RaytraceLightSrcTexture);
2332 if (!myOpenGlFBO.IsNull())
2334 myOpenGlFBO->ColorTexture()->Unbind (theGlContext, GL_TEXTURE0 + OpenGl_RT_OpenGlColorTexture);
2335 myOpenGlFBO->DepthStencilTexture()->Unbind (theGlContext, GL_TEXTURE0 + OpenGl_RT_OpenGlDepthTexture);
2338 theGlContext->core15fwd->glActiveTexture (GL_TEXTURE0);
2341 // =======================================================================
2342 // function : runRaytraceShaders
2343 // purpose : Runs ray-tracing shader programs
2344 // =======================================================================
2345 Standard_Boolean OpenGl_View::runRaytraceShaders (const Standard_Integer theSizeX,
2346 const Standard_Integer theSizeY,
2347 const OpenGl_Vec3* theOrigins,
2348 const OpenGl_Vec3* theDirects,
2349 const OpenGl_Mat4& theUnviewMat,
2350 OpenGl_FrameBuffer* theReadDrawFbo,
2351 const Handle(OpenGl_Context)& theGlContext)
2353 bindRaytraceTextures (theGlContext);
2355 Handle(OpenGl_FrameBuffer) aRenderFramebuffer;
2356 Handle(OpenGl_FrameBuffer) anAccumFramebuffer;
2358 if (myRaytraceParameters.GlobalIllumination) // if path-tracing is used
2360 for (int anIdx = 0; anIdx < 3; ++anIdx)
2362 if (fabsf (theOrigins[anIdx].x() - myPreviousOrigins[anIdx].x()) > std::numeric_limits<Standard_ShortReal>::epsilon()
2363 || fabsf (theOrigins[anIdx].y() - myPreviousOrigins[anIdx].y()) > std::numeric_limits<Standard_ShortReal>::epsilon()
2364 || fabsf (theOrigins[anIdx].z() - myPreviousOrigins[anIdx].z()) > std::numeric_limits<Standard_ShortReal>::epsilon())
2366 myAccumFrames = 0; // camera has been moved
2369 myPreviousOrigins[anIdx] = theOrigins[anIdx];
2372 aRenderFramebuffer = myAccumFrames % 2 ? myRaytraceFBO1 : myRaytraceFBO2;
2373 anAccumFramebuffer = myAccumFrames % 2 ? myRaytraceFBO2 : myRaytraceFBO1;
2375 anAccumFramebuffer->ColorTexture()->Bind (
2376 theGlContext, GL_TEXTURE0 + OpenGl_RT_PrevAccumTexture);
2378 aRenderFramebuffer->BindBuffer (theGlContext);
2380 else if (myRenderParams.IsAntialiasingEnabled) // if 2-pass ray-tracing is used
2382 myRaytraceFBO1->BindBuffer (theGlContext);
2384 glDisable (GL_BLEND);
2387 Standard_Boolean aResult = theGlContext->BindProgram (myRaytraceProgram);
2389 aResult &= setUniformState (theOrigins,
2392 0, // ID of RT program
2395 if (myRaytraceParameters.GlobalIllumination)
2397 if (myAccumFrames == 0)
2402 // Set frame accumulation weight
2403 myRaytraceProgram->SetUniform (theGlContext,
2404 myUniformLocations[0][OpenGl_RT_uSampleWeight], 1.f / (myAccumFrames + 1));
2406 // Set random number generator seed
2407 myRaytraceProgram->SetUniform (theGlContext,
2408 myUniformLocations[0][OpenGl_RT_uFrameRndSeed], static_cast<Standard_Integer> (myRNG.NextInt() >> 2));
2411 theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
2413 if (myRaytraceParameters.GlobalIllumination)
2415 // Output accumulated image
2416 glDisable (GL_BLEND);
2418 theGlContext->BindProgram (myOutImageProgram);
2420 if (theReadDrawFbo != NULL)
2422 theReadDrawFbo->BindBuffer (theGlContext);
2426 aRenderFramebuffer->UnbindBuffer (theGlContext);
2429 aRenderFramebuffer->ColorTexture()->Bind (
2430 theGlContext, GL_TEXTURE0 + OpenGl_RT_PrevAccumTexture);
2432 theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
2436 else if (myRenderParams.IsAntialiasingEnabled)
2438 myRaytraceFBO1->ColorTexture()->Bind (theGlContext, GL_TEXTURE0 + OpenGl_RT_FsaaInputTexture);
2440 aResult &= theGlContext->BindProgram (myPostFSAAProgram);
2442 aResult &= setUniformState (theOrigins,
2445 1, // ID of FSAA program
2448 // Perform multi-pass adaptive FSAA using ping-pong technique.
2449 // We use 'FLIPTRI' sampling pattern changing for every pixel
2450 // (3 additional samples per pixel, the 1st sample is already
2451 // available from initial ray-traced image).
2452 for (Standard_Integer anIt = 1; anIt < 4; ++anIt)
2454 GLfloat aOffsetX = 1.f / theSizeX;
2455 GLfloat aOffsetY = 1.f / theSizeY;
2473 aResult &= myPostFSAAProgram->SetUniform (theGlContext,
2474 myUniformLocations[1][OpenGl_RT_uSamples], anIt + 1);
2475 aResult &= myPostFSAAProgram->SetUniform (theGlContext,
2476 myUniformLocations[1][OpenGl_RT_uOffsetX], aOffsetX);
2477 aResult &= myPostFSAAProgram->SetUniform (theGlContext,
2478 myUniformLocations[1][OpenGl_RT_uOffsetY], aOffsetY);
2480 Handle(OpenGl_FrameBuffer)& aFramebuffer = anIt % 2 ? myRaytraceFBO2 : myRaytraceFBO1;
2482 if (anIt == 3) // disable FBO on last iteration
2484 if (theReadDrawFbo != NULL)
2486 theReadDrawFbo->BindBuffer (theGlContext);
2490 aFramebuffer->UnbindBuffer (theGlContext);
2495 aFramebuffer->BindBuffer (theGlContext);
2498 theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
2500 if (anIt != 3) // set input for the next pass
2502 aFramebuffer->ColorTexture()->Bind (theGlContext, GL_TEXTURE0 + OpenGl_RT_FsaaInputTexture);
2507 unbindRaytraceTextures (theGlContext);
2509 theGlContext->BindProgram (NULL);
2514 // =======================================================================
2515 // function : raytrace
2516 // purpose : Redraws the window using OpenGL/GLSL ray-tracing
2517 // =======================================================================
2518 Standard_Boolean OpenGl_View::raytrace (const Standard_Integer theSizeX,
2519 const Standard_Integer theSizeY,
2520 OpenGl_FrameBuffer* theReadDrawFbo,
2521 const Handle(OpenGl_Context)& theGlContext)
2523 if (!initRaytraceResources (theGlContext))
2525 return Standard_False;
2528 if (!resizeRaytraceBuffers (theSizeX, theSizeY, theGlContext))
2530 return Standard_False;
2533 if (!updateRaytraceEnvironmentMap (theGlContext))
2535 return Standard_False;
2538 // Get model-view and projection matrices
2539 OpenGl_Mat4 aOrientationMatrix = myCamera->OrientationMatrixF();
2540 OpenGl_Mat4 aViewMappingMatrix = theGlContext->ProjectionState.Current();
2542 OpenGl_Mat4 aInverOrientMatrix;
2543 aOrientationMatrix.Inverted (aInverOrientMatrix);
2544 if (!updateRaytraceLightSources (aInverOrientMatrix, theGlContext))
2546 return Standard_False;
2549 OpenGl_Vec3 aOrigins[4];
2550 OpenGl_Vec3 aDirects[4];
2551 OpenGl_Mat4 anUnviewMat;
2553 updateCamera (aOrientationMatrix,
2559 glDisable (GL_BLEND);
2560 glDisable (GL_DEPTH_TEST);
2562 if (theReadDrawFbo != NULL)
2564 theReadDrawFbo->BindBuffer (theGlContext);
2567 // Generate ray-traced image
2568 if (myIsRaytraceDataValid)
2570 myRaytraceScreenQuad.BindVertexAttrib (theGlContext, Graphic3d_TOA_POS);
2572 if (!myRaytraceGeometry.AcquireTextures (theGlContext))
2574 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB, GL_DEBUG_TYPE_ERROR_ARB,
2575 0, GL_DEBUG_SEVERITY_MEDIUM_ARB, "Error: Failed to acquire OpenGL image textures");
2578 Standard_Boolean aResult = runRaytraceShaders (theSizeX,
2588 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB, GL_DEBUG_TYPE_ERROR_ARB,
2589 0, GL_DEBUG_SEVERITY_MEDIUM_ARB, "Error: Failed to execute ray-tracing shaders");
2592 if (!myRaytraceGeometry.ReleaseTextures (theGlContext))
2594 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB, GL_DEBUG_TYPE_ERROR_ARB,
2595 0, GL_DEBUG_SEVERITY_MEDIUM_ARB, "Error: Failed to release OpenGL image textures");
2598 myRaytraceScreenQuad.UnbindVertexAttrib (theGlContext, Graphic3d_TOA_POS);
2601 glDisable (GL_BLEND);
2602 glEnable (GL_DEPTH_TEST);
2604 return Standard_True;