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 <OpenGl_GlCore44.hxx>
22 #include <OSD_Protection.hxx>
23 #include <OSD_File.hxx>
25 #include "../Shaders/Shaders_RaytraceBase_vs.pxx"
26 #include "../Shaders/Shaders_RaytraceBase_fs.pxx"
27 #include "../Shaders/Shaders_PathtraceBase_fs.pxx"
28 #include "../Shaders/Shaders_RaytraceRender_fs.pxx"
29 #include "../Shaders/Shaders_RaytraceSmooth_fs.pxx"
30 #include "../Shaders/Shaders_Display_fs.pxx"
32 using namespace OpenGl_Raytrace;
34 //! Use this macro to output ray-tracing debug info
35 // #define RAY_TRACE_PRINT_INFO
37 #ifdef RAY_TRACE_PRINT_INFO
38 #include <OSD_Timer.hxx>
43 static const OpenGl_Vec4 THE_WHITE_COLOR (1.0f, 1.0f, 1.0f, 1.0f);
44 static const OpenGl_Vec4 THE_BLACK_COLOR (0.0f, 0.0f, 0.0f, 1.0f);
47 // =======================================================================
48 // function : updateRaytraceGeometry
49 // purpose : Updates 3D scene geometry for ray-tracing
50 // =======================================================================
51 Standard_Boolean OpenGl_View::updateRaytraceGeometry (const RaytraceUpdateMode theMode,
52 const Standard_Integer theViewId,
53 const Handle(OpenGl_Context)& theGlContext)
55 // In 'check' mode (OpenGl_GUM_CHECK) the scene geometry is analyzed for
56 // modifications. This is light-weight procedure performed on each frame
57 if (theMode == OpenGl_GUM_CHECK)
59 if (myRaytraceLayerListState != myZLayers.ModificationStateOfRaytracable())
61 return updateRaytraceGeometry (OpenGl_GUM_PREPARE, theViewId, theGlContext);
64 else if (theMode == OpenGl_GUM_PREPARE)
66 myRaytraceGeometry.ClearMaterials();
68 myArrayToTrianglesMap.clear();
70 myIsRaytraceDataValid = Standard_False;
73 // The set of processed structures (reflected to ray-tracing)
74 // This set is used to remove out-of-date records from the
75 // hash map of structures
76 std::set<const OpenGl_Structure*> anElements;
78 // Set to store all currently visible OpenGL primitive arrays
79 // applicable for ray-tracing
80 std::set<Standard_Size> anArrayIDs;
82 // Set to store all non-raytracable elements allowing tracking
83 // of changes in OpenGL scene (only for path tracing)
84 std::set<Standard_Integer> aNonRaytraceIDs;
86 const OpenGl_Layer& aLayer = myZLayers.Layer (Graphic3d_ZLayerId_Default);
88 if (aLayer.NbStructures() != 0)
90 const OpenGl_ArrayOfIndexedMapOfStructure& aStructArray = aLayer.ArrayOfStructures();
92 for (Standard_Integer anIndex = 0; anIndex < aStructArray.Length(); ++anIndex)
94 for (OpenGl_IndexedMapOfStructure::Iterator aStructIt (aStructArray (anIndex)); aStructIt.More(); aStructIt.Next())
96 const OpenGl_Structure* aStructure = aStructIt.Value();
98 if (theMode == OpenGl_GUM_CHECK)
100 if (toUpdateStructure (aStructure))
102 return updateRaytraceGeometry (OpenGl_GUM_PREPARE, theViewId, theGlContext);
104 else if (aStructure->IsVisible() && myRaytraceParameters.GlobalIllumination)
106 aNonRaytraceIDs.insert (aStructure->highlight ? aStructure->Id : -aStructure->Id);
109 else if (theMode == OpenGl_GUM_PREPARE)
111 if (!aStructure->IsRaytracable() || !aStructure->IsVisible())
115 else if (!aStructure->ViewAffinity.IsNull() && !aStructure->ViewAffinity->IsVisible (theViewId))
120 for (OpenGl_Structure::GroupIterator aGroupIter (aStructure->Groups()); aGroupIter.More(); aGroupIter.Next())
122 // Extract OpenGL elements from the group (primitives arrays)
123 for (const OpenGl_ElementNode* aNode = aGroupIter.Value()->FirstNode(); aNode != NULL; aNode = aNode->next)
125 OpenGl_PrimitiveArray* aPrimArray = dynamic_cast<OpenGl_PrimitiveArray*> (aNode->elem);
127 if (aPrimArray != NULL)
129 anArrayIDs.insert (aPrimArray->GetUID());
134 else if (theMode == OpenGl_GUM_REBUILD)
136 if (!aStructure->IsRaytracable())
140 else if (addRaytraceStructure (aStructure, theGlContext))
142 anElements.insert (aStructure); // structure was processed
149 if (theMode == OpenGl_GUM_PREPARE)
151 BVH_ObjectSet<Standard_ShortReal, 3>::BVH_ObjectList anUnchangedObjects;
153 // Filter out unchanged objects so only their transformations and materials
154 // will be updated (and newly added objects will be processed from scratch)
155 for (Standard_Integer anObjIdx = 0; anObjIdx < myRaytraceGeometry.Size(); ++anObjIdx)
157 OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
158 myRaytraceGeometry.Objects().ChangeValue (anObjIdx).operator->());
160 if (aTriangleSet == NULL)
165 if (anArrayIDs.find (aTriangleSet->AssociatedPArrayID()) != anArrayIDs.end())
167 anUnchangedObjects.Append (myRaytraceGeometry.Objects().Value (anObjIdx));
169 myArrayToTrianglesMap[aTriangleSet->AssociatedPArrayID()] = aTriangleSet;
173 myRaytraceGeometry.Objects() = anUnchangedObjects;
175 return updateRaytraceGeometry (OpenGl_GUM_REBUILD, theViewId, theGlContext);
177 else if (theMode == OpenGl_GUM_REBUILD)
179 // Actualize the hash map of structures - remove out-of-date records
180 std::map<const OpenGl_Structure*, StructState>::iterator anIter = myStructureStates.begin();
182 while (anIter != myStructureStates.end())
184 if (anElements.find (anIter->first) == anElements.end())
186 myStructureStates.erase (anIter++);
194 // Actualize OpenGL layer list state
195 myRaytraceLayerListState = myZLayers.ModificationStateOfRaytracable();
197 // Rebuild two-level acceleration structure
198 myRaytraceGeometry.ProcessAcceleration();
200 myRaytraceSceneRadius = 2.f /* scale factor */ * std::max (
201 myRaytraceGeometry.Box().CornerMin().cwiseAbs().maxComp(),
202 myRaytraceGeometry.Box().CornerMax().cwiseAbs().maxComp());
204 const BVH_Vec3f aSize = myRaytraceGeometry.Box().Size();
206 myRaytraceSceneEpsilon = Max (1.0e-6f, 1.0e-4f * aSize.Modulus());
208 return uploadRaytraceData (theGlContext);
211 if (myRaytraceParameters.GlobalIllumination)
213 Standard_Boolean toRestart =
214 aNonRaytraceIDs.size() != myNonRaytraceStructureIDs.size();
216 for (std::set<Standard_Integer>::iterator anID = aNonRaytraceIDs.begin(); anID != aNonRaytraceIDs.end() && !toRestart; ++anID)
218 if (myNonRaytraceStructureIDs.find (*anID) == myNonRaytraceStructureIDs.end())
220 toRestart = Standard_True;
229 myNonRaytraceStructureIDs = aNonRaytraceIDs;
232 return Standard_True;
235 // =======================================================================
236 // function : toUpdateStructure
237 // purpose : Checks to see if the structure is modified
238 // =======================================================================
239 Standard_Boolean OpenGl_View::toUpdateStructure (const OpenGl_Structure* theStructure)
241 if (!theStructure->IsRaytracable())
243 if (theStructure->ModificationState() > 0)
245 theStructure->ResetModificationState();
247 return Standard_True; // ray-trace element was removed - need to rebuild
250 return Standard_False; // did not contain ray-trace elements
253 std::map<const OpenGl_Structure*, StructState>::iterator aStructState = myStructureStates.find (theStructure);
255 if (aStructState == myStructureStates.end() || aStructState->second.StructureState != theStructure->ModificationState())
257 return Standard_True;
259 else if (theStructure->InstancedStructure() != NULL)
261 return aStructState->second.InstancedState != theStructure->InstancedStructure()->ModificationState();
264 return Standard_False;
267 // =======================================================================
268 // function : buildTextureTransform
269 // purpose : Constructs texture transformation matrix
270 // =======================================================================
271 void buildTextureTransform (const Handle(Graphic3d_TextureParams)& theParams, BVH_Mat4f& theMatrix)
273 theMatrix.InitIdentity();
276 const Graphic3d_Vec2& aScale = theParams->Scale();
278 theMatrix.ChangeValue (0, 0) *= aScale.x();
279 theMatrix.ChangeValue (1, 0) *= aScale.x();
280 theMatrix.ChangeValue (2, 0) *= aScale.x();
281 theMatrix.ChangeValue (3, 0) *= aScale.x();
283 theMatrix.ChangeValue (0, 1) *= aScale.y();
284 theMatrix.ChangeValue (1, 1) *= aScale.y();
285 theMatrix.ChangeValue (2, 1) *= aScale.y();
286 theMatrix.ChangeValue (3, 1) *= aScale.y();
289 const Graphic3d_Vec2 aTrans = -theParams->Translation();
291 theMatrix.ChangeValue (0, 3) = theMatrix.GetValue (0, 0) * aTrans.x() +
292 theMatrix.GetValue (0, 1) * aTrans.y();
294 theMatrix.ChangeValue (1, 3) = theMatrix.GetValue (1, 0) * aTrans.x() +
295 theMatrix.GetValue (1, 1) * aTrans.y();
297 theMatrix.ChangeValue (2, 3) = theMatrix.GetValue (2, 0) * aTrans.x() +
298 theMatrix.GetValue (2, 1) * aTrans.y();
301 const Standard_ShortReal aSin = std::sin (
302 -theParams->Rotation() * static_cast<Standard_ShortReal> (M_PI / 180.0));
303 const Standard_ShortReal aCos = std::cos (
304 -theParams->Rotation() * static_cast<Standard_ShortReal> (M_PI / 180.0));
306 BVH_Mat4f aRotationMat;
307 aRotationMat.SetValue (0, 0, aCos);
308 aRotationMat.SetValue (1, 1, aCos);
309 aRotationMat.SetValue (0, 1, -aSin);
310 aRotationMat.SetValue (1, 0, aSin);
312 theMatrix = theMatrix * aRotationMat;
315 // =======================================================================
316 // function : convertMaterial
317 // purpose : Creates ray-tracing material properties
318 // =======================================================================
319 OpenGl_RaytraceMaterial OpenGl_View::convertMaterial (const OpenGl_AspectFace* theAspect,
320 const Handle(OpenGl_Context)& theGlContext)
322 OpenGl_RaytraceMaterial theMaterial;
324 const Graphic3d_MaterialAspect& aSrcMat = theAspect->Aspect()->FrontMaterial();
325 const OpenGl_Vec3& aMatCol = theAspect->Aspect()->InteriorColor();
326 const float aShine = 128.0f * float(aSrcMat.Shininess());
327 const bool isPhysic = aSrcMat.MaterialType (Graphic3d_MATERIAL_PHYSIC) == Standard_True;
330 if (aSrcMat.ReflectionMode (Graphic3d_TOR_AMBIENT))
332 const OpenGl_Vec3& aSrcAmb = isPhysic ? aSrcMat.AmbientColor() : aMatCol;
333 theMaterial.Ambient = BVH_Vec4f (aSrcAmb * (float )aSrcMat.Ambient(), 1.0f);
337 theMaterial.Ambient = THE_BLACK_COLOR;
340 // diffusion component
341 if (aSrcMat.ReflectionMode (Graphic3d_TOR_DIFFUSE))
343 const OpenGl_Vec3& aSrcDif = isPhysic ? aSrcMat.DiffuseColor() : aMatCol;
344 theMaterial.Diffuse = BVH_Vec4f (aSrcDif * (float )aSrcMat.Diffuse(), -1.0f); // -1 is no texture
348 theMaterial.Diffuse = BVH_Vec4f (THE_BLACK_COLOR.rgb(), -1.0f);
351 // specular component
352 if (aSrcMat.ReflectionMode (Graphic3d_TOR_SPECULAR))
354 const OpenGl_Vec3& aSrcSpe = aSrcMat.SpecularColor();
355 const OpenGl_Vec3& aSrcSpe2 = isPhysic ? aSrcSpe : THE_WHITE_COLOR.rgb();
356 theMaterial.Specular = BVH_Vec4f (aSrcSpe2 * (float )aSrcMat.Specular(), aShine);
358 const Standard_ShortReal aMaxRefl = Max (theMaterial.Diffuse.x() + theMaterial.Specular.x(),
359 Max (theMaterial.Diffuse.y() + theMaterial.Specular.y(),
360 theMaterial.Diffuse.z() + theMaterial.Specular.z()));
362 const Standard_ShortReal aReflectionScale = 0.75f / aMaxRefl;
364 // ignore isPhysic here
365 theMaterial.Reflection = BVH_Vec4f (aSrcSpe * (float )aSrcMat.Specular() * aReflectionScale, 0.0f);
369 theMaterial.Specular = BVH_Vec4f (THE_BLACK_COLOR.rgb(), aShine);
372 // emission component
373 if (aSrcMat.ReflectionMode (Graphic3d_TOR_EMISSION))
375 const OpenGl_Vec3& aSrcEms = isPhysic ? aSrcMat.EmissiveColor() : aMatCol;
376 theMaterial.Emission = BVH_Vec4f (aSrcEms * (float )aSrcMat.Emissive(), 1.0f);
380 theMaterial.Emission = THE_BLACK_COLOR;
383 const float anIndex = (float )aSrcMat.RefractionIndex();
384 theMaterial.Transparency = BVH_Vec4f (1.0f - (float )aSrcMat.Transparency(),
385 (float )aSrcMat.Transparency(),
386 anIndex == 0 ? 1.0f : anIndex,
387 anIndex == 0 ? 1.0f : 1.0f / anIndex);
389 // Serialize physically-based material properties
390 const Graphic3d_BSDF& aBSDF = aSrcMat.BSDF();
392 theMaterial.BSDF.Le = BVH_Vec4f (aBSDF.Le, 0.f);
393 theMaterial.BSDF.Kd = BVH_Vec4f (aBSDF.Kd, -1.f /* no tex */);
394 theMaterial.BSDF.Kr = BVH_Vec4f (aBSDF.Kr, 0.f);
395 theMaterial.BSDF.Kt = BVH_Vec4f (aBSDF.Kt, 0.f);
396 theMaterial.BSDF.Ks = BVH_Vec4f (aBSDF.Ks, aBSDF.Roughness);
398 theMaterial.BSDF.Fresnel = aBSDF.Fresnel.Serialize();
400 theMaterial.BSDF.Absorption = BVH_Vec4f (aBSDF.AbsorptionColor,
401 aBSDF.AbsorptionCoeff);
403 // Handle material textures
404 if (theAspect->Aspect()->ToMapTexture())
406 if (theGlContext->HasRayTracingTextures())
408 buildTextureTransform (theAspect->TextureParams(), theMaterial.TextureTransform);
410 // write texture ID to diffuse w-component
411 theMaterial.Diffuse.w() = theMaterial.BSDF.Kd.w() =
412 static_cast<Standard_ShortReal> (myRaytraceGeometry.AddTexture (theAspect->TextureRes (theGlContext)));
414 else if (!myIsRaytraceWarnTextures)
416 const TCollection_ExtendedString aWarnMessage =
417 "Warning: texturing in Ray-Trace requires GL_ARB_bindless_texture extension which is missing. "
418 "Please try to update graphics card driver. At the moment textures will be ignored.";
420 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
421 GL_DEBUG_TYPE_PORTABILITY, 0, GL_DEBUG_SEVERITY_HIGH, aWarnMessage);
423 myIsRaytraceWarnTextures = Standard_True;
430 // =======================================================================
431 // function : addRaytraceStructure
432 // purpose : Adds OpenGL structure to ray-traced scene geometry
433 // =======================================================================
434 Standard_Boolean OpenGl_View::addRaytraceStructure (const OpenGl_Structure* theStructure,
435 const Handle(OpenGl_Context)& theGlContext)
437 if (!theStructure->IsVisible())
439 myStructureStates[theStructure] = StructState (theStructure);
441 return Standard_True;
444 // Get structure material
445 OpenGl_RaytraceMaterial aDefaultMaterial;
446 Standard_Boolean aResult = addRaytraceGroups (theStructure, aDefaultMaterial, theStructure->Transformation(), theGlContext);
448 // Process all connected OpenGL structures
449 const OpenGl_Structure* anInstanced = theStructure->InstancedStructure();
451 if (anInstanced != NULL && anInstanced->IsRaytracable())
453 aResult &= addRaytraceGroups (anInstanced, aDefaultMaterial, theStructure->Transformation(), theGlContext);
456 myStructureStates[theStructure] = StructState (theStructure);
461 // =======================================================================
462 // function : addRaytraceGroups
463 // purpose : Adds OpenGL groups to ray-traced scene geometry
464 // =======================================================================
465 Standard_Boolean OpenGl_View::addRaytraceGroups (const OpenGl_Structure* theStructure,
466 const OpenGl_RaytraceMaterial& theStructMat,
467 const Handle(Geom_Transformation)& theTrsf,
468 const Handle(OpenGl_Context)& theGlContext)
471 for (OpenGl_Structure::GroupIterator aGroupIter (theStructure->Groups()); aGroupIter.More(); aGroupIter.Next())
473 // Get group material
474 OpenGl_RaytraceMaterial aGroupMaterial;
475 if (aGroupIter.Value()->AspectFace() != NULL)
477 aGroupMaterial = convertMaterial (
478 aGroupIter.Value()->AspectFace(), theGlContext);
481 Standard_Integer aMatID = static_cast<Standard_Integer> (myRaytraceGeometry.Materials.size());
483 // Use group material if available, otherwise use structure material
484 myRaytraceGeometry.Materials.push_back (
485 aGroupIter.Value()->AspectFace() != NULL ? aGroupMaterial : theStructMat);
487 // Add OpenGL elements from group (extract primitives arrays and aspects)
488 for (const OpenGl_ElementNode* aNode = aGroupIter.Value()->FirstNode(); aNode != NULL; aNode = aNode->next)
490 OpenGl_AspectFace* anAspect = dynamic_cast<OpenGl_AspectFace*> (aNode->elem);
492 if (anAspect != NULL)
494 aMatID = static_cast<Standard_Integer> (myRaytraceGeometry.Materials.size());
496 OpenGl_RaytraceMaterial aMaterial = convertMaterial (anAspect, theGlContext);
498 myRaytraceGeometry.Materials.push_back (aMaterial);
502 OpenGl_PrimitiveArray* aPrimArray = dynamic_cast<OpenGl_PrimitiveArray*> (aNode->elem);
504 if (aPrimArray != NULL)
506 std::map<Standard_Size, OpenGl_TriangleSet*>::iterator aSetIter = myArrayToTrianglesMap.find (aPrimArray->GetUID());
508 if (aSetIter != myArrayToTrianglesMap.end())
510 OpenGl_TriangleSet* aSet = aSetIter->second;
512 BVH_Transform<Standard_ShortReal, 4>* aTransform = new BVH_Transform<Standard_ShortReal, 4>();
514 if (!theTrsf.IsNull())
516 theTrsf->Trsf().GetMat4 (aMat4);
517 aTransform->SetTransform (aMat4);
520 aSet->SetProperties (aTransform);
522 if (aSet->MaterialIndex() != OpenGl_TriangleSet::INVALID_MATERIAL && aSet->MaterialIndex() != aMatID)
524 aSet->SetMaterialIndex (aMatID);
529 NCollection_Handle<BVH_Object<Standard_ShortReal, 3> > aSet =
530 addRaytracePrimitiveArray (aPrimArray, aMatID, 0);
534 BVH_Transform<Standard_ShortReal, 4>* aTransform = new BVH_Transform<Standard_ShortReal, 4>;
536 if (!theTrsf.IsNull())
538 theTrsf->Trsf().GetMat4 (aMat4);
539 aTransform->SetTransform (aMat4);
542 aSet->SetProperties (aTransform);
544 myRaytraceGeometry.Objects().Append (aSet);
552 return Standard_True;
555 // =======================================================================
556 // function : addRaytracePrimitiveArray
557 // purpose : Adds OpenGL primitive array to ray-traced scene geometry
558 // =======================================================================
559 OpenGl_TriangleSet* OpenGl_View::addRaytracePrimitiveArray (const OpenGl_PrimitiveArray* theArray,
560 const Standard_Integer theMaterial,
561 const OpenGl_Mat4* theTransform)
563 const Handle(Graphic3d_BoundBuffer)& aBounds = theArray->Bounds();
564 const Handle(Graphic3d_IndexBuffer)& anIndices = theArray->Indices();
565 const Handle(Graphic3d_Buffer)& anAttribs = theArray->Attributes();
567 if (theArray->DrawMode() < GL_TRIANGLES
568 #ifndef GL_ES_VERSION_2_0
569 || theArray->DrawMode() > GL_POLYGON
571 || theArray->DrawMode() > GL_TRIANGLE_FAN
573 || anAttribs.IsNull())
578 OpenGl_Mat4 aNormalMatrix;
580 if (theTransform != NULL)
582 Standard_ASSERT_RETURN (theTransform->Inverted (aNormalMatrix),
583 "Error: Failed to compute normal transformation matrix", NULL);
585 aNormalMatrix.Transpose();
588 OpenGl_TriangleSet* aSet = new OpenGl_TriangleSet (theArray->GetUID());
590 aSet->Vertices.reserve (anAttribs->NbElements);
591 aSet->Normals.reserve (anAttribs->NbElements);
592 aSet->TexCrds.reserve (anAttribs->NbElements);
594 const size_t aVertFrom = aSet->Vertices.size();
596 for (Standard_Integer anAttribIter = 0; anAttribIter < anAttribs->NbAttributes; ++anAttribIter)
598 const Graphic3d_Attribute& anAttrib = anAttribs->Attribute (anAttribIter);
599 const size_t anOffset = anAttribs->AttributeOffset (anAttribIter);
600 if (anAttrib.Id == Graphic3d_TOA_POS)
602 if (anAttrib.DataType == Graphic3d_TOD_VEC3
603 || anAttrib.DataType == Graphic3d_TOD_VEC4)
605 for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
607 aSet->Vertices.push_back (
608 *reinterpret_cast<const Graphic3d_Vec3*> (anAttribs->value (aVertIter) + anOffset));
611 else if (anAttrib.DataType == Graphic3d_TOD_VEC2)
613 for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
615 const Standard_ShortReal* aCoords =
616 reinterpret_cast<const Standard_ShortReal*> (anAttribs->value (aVertIter) + anOffset);
618 aSet->Vertices.push_back (BVH_Vec3f (aCoords[0], aCoords[1], 0.0f));
622 else if (anAttrib.Id == Graphic3d_TOA_NORM)
624 if (anAttrib.DataType == Graphic3d_TOD_VEC3
625 || anAttrib.DataType == Graphic3d_TOD_VEC4)
627 for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
629 aSet->Normals.push_back (
630 *reinterpret_cast<const Graphic3d_Vec3*> (anAttribs->value (aVertIter) + anOffset));
634 else if (anAttrib.Id == Graphic3d_TOA_UV)
636 if (anAttrib.DataType == Graphic3d_TOD_VEC2)
638 for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
640 aSet->TexCrds.push_back (
641 *reinterpret_cast<const Graphic3d_Vec2*> (anAttribs->value (aVertIter) + anOffset));
647 if (aSet->Normals.size() != aSet->Vertices.size())
649 for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
651 aSet->Normals.push_back (BVH_Vec3f());
655 if (aSet->TexCrds.size() != aSet->Vertices.size())
657 for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
659 aSet->TexCrds.push_back (BVH_Vec2f());
663 if (theTransform != NULL)
665 for (size_t aVertIter = aVertFrom; aVertIter < aSet->Vertices.size(); ++aVertIter)
667 BVH_Vec3f& aVertex = aSet->Vertices[aVertIter];
669 BVH_Vec4f aTransVertex = *theTransform *
670 BVH_Vec4f (aVertex.x(), aVertex.y(), aVertex.z(), 1.f);
672 aVertex = BVH_Vec3f (aTransVertex.x(), aTransVertex.y(), aTransVertex.z());
674 for (size_t aVertIter = aVertFrom; aVertIter < aSet->Normals.size(); ++aVertIter)
676 BVH_Vec3f& aNormal = aSet->Normals[aVertIter];
678 BVH_Vec4f aTransNormal = aNormalMatrix *
679 BVH_Vec4f (aNormal.x(), aNormal.y(), aNormal.z(), 0.f);
681 aNormal = BVH_Vec3f (aTransNormal.x(), aTransNormal.y(), aTransNormal.z());
685 if (!aBounds.IsNull())
687 for (Standard_Integer aBound = 0, aBoundStart = 0; aBound < aBounds->NbBounds; ++aBound)
689 const Standard_Integer aVertNum = aBounds->Bounds[aBound];
691 if (!addRaytraceVertexIndices (*aSet, theMaterial, aVertNum, aBoundStart, *theArray))
697 aBoundStart += aVertNum;
702 const Standard_Integer aVertNum = !anIndices.IsNull() ? anIndices->NbElements : anAttribs->NbElements;
704 if (!addRaytraceVertexIndices (*aSet, theMaterial, aVertNum, 0, *theArray))
712 if (aSet->Size() != 0)
720 // =======================================================================
721 // function : addRaytraceVertexIndices
722 // purpose : Adds vertex indices to ray-traced scene geometry
723 // =======================================================================
724 Standard_Boolean OpenGl_View::addRaytraceVertexIndices (OpenGl_TriangleSet& theSet,
725 const Standard_Integer theMatID,
726 const Standard_Integer theCount,
727 const Standard_Integer theOffset,
728 const OpenGl_PrimitiveArray& theArray)
730 switch (theArray.DrawMode())
732 case GL_TRIANGLES: return addRaytraceTriangleArray (theSet, theMatID, theCount, theOffset, theArray.Indices());
733 case GL_TRIANGLE_FAN: return addRaytraceTriangleFanArray (theSet, theMatID, theCount, theOffset, theArray.Indices());
734 case GL_TRIANGLE_STRIP: return addRaytraceTriangleStripArray (theSet, theMatID, theCount, theOffset, theArray.Indices());
735 #if !defined(GL_ES_VERSION_2_0)
736 case GL_QUAD_STRIP: return addRaytraceQuadrangleStripArray (theSet, theMatID, theCount, theOffset, theArray.Indices());
737 case GL_QUADS: return addRaytraceQuadrangleArray (theSet, theMatID, theCount, theOffset, theArray.Indices());
738 case GL_POLYGON: return addRaytracePolygonArray (theSet, theMatID, theCount, theOffset, theArray.Indices());
742 return Standard_False;
745 // =======================================================================
746 // function : addRaytraceTriangleArray
747 // purpose : Adds OpenGL triangle array to ray-traced scene geometry
748 // =======================================================================
749 Standard_Boolean OpenGl_View::addRaytraceTriangleArray (OpenGl_TriangleSet& theSet,
750 const Standard_Integer theMatID,
751 const Standard_Integer theCount,
752 const Standard_Integer theOffset,
753 const Handle(Graphic3d_IndexBuffer)& theIndices)
757 return Standard_True;
760 theSet.Elements.reserve (theSet.Elements.size() + theCount / 3);
762 if (!theIndices.IsNull())
764 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; aVert += 3)
766 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0),
767 theIndices->Index (aVert + 1),
768 theIndices->Index (aVert + 2),
774 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; aVert += 3)
776 theSet.Elements.push_back (BVH_Vec4i (aVert + 0, aVert + 1, aVert + 2, theMatID));
780 return Standard_True;
783 // =======================================================================
784 // function : addRaytraceTriangleFanArray
785 // purpose : Adds OpenGL triangle fan array to ray-traced scene geometry
786 // =======================================================================
787 Standard_Boolean OpenGl_View::addRaytraceTriangleFanArray (OpenGl_TriangleSet& theSet,
788 const Standard_Integer theMatID,
789 const Standard_Integer theCount,
790 const Standard_Integer theOffset,
791 const Handle(Graphic3d_IndexBuffer)& theIndices)
795 return Standard_True;
798 theSet.Elements.reserve (theSet.Elements.size() + theCount - 2);
800 if (!theIndices.IsNull())
802 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
804 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (theOffset),
805 theIndices->Index (aVert + 1),
806 theIndices->Index (aVert + 2),
812 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
814 theSet.Elements.push_back (BVH_Vec4i (theOffset,
821 return Standard_True;
824 // =======================================================================
825 // function : addRaytraceTriangleStripArray
826 // purpose : Adds OpenGL triangle strip array to ray-traced scene geometry
827 // =======================================================================
828 Standard_Boolean OpenGl_View::addRaytraceTriangleStripArray (OpenGl_TriangleSet& theSet,
829 const Standard_Integer theMatID,
830 const Standard_Integer theCount,
831 const Standard_Integer theOffset,
832 const Handle(Graphic3d_IndexBuffer)& theIndices)
836 return Standard_True;
839 theSet.Elements.reserve (theSet.Elements.size() + theCount - 2);
841 if (!theIndices.IsNull())
843 for (Standard_Integer aVert = theOffset, aCW = 0; aVert < theOffset + theCount - 2; ++aVert, aCW = (aCW + 1) % 2)
845 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + (aCW ? 1 : 0)),
846 theIndices->Index (aVert + (aCW ? 0 : 1)),
847 theIndices->Index (aVert + 2),
853 for (Standard_Integer aVert = theOffset, aCW = 0; aVert < theOffset + theCount - 2; ++aVert, aCW = (aCW + 1) % 2)
855 theSet.Elements.push_back (BVH_Vec4i (aVert + (aCW ? 1 : 0),
856 aVert + (aCW ? 0 : 1),
862 return Standard_True;
865 // =======================================================================
866 // function : addRaytraceQuadrangleArray
867 // purpose : Adds OpenGL quad array to ray-traced scene geometry
868 // =======================================================================
869 Standard_Boolean OpenGl_View::addRaytraceQuadrangleArray (OpenGl_TriangleSet& theSet,
870 const Standard_Integer theMatID,
871 const Standard_Integer theCount,
872 const Standard_Integer theOffset,
873 const Handle(Graphic3d_IndexBuffer)& theIndices)
877 return Standard_True;
880 theSet.Elements.reserve (theSet.Elements.size() + theCount / 2);
882 if (!theIndices.IsNull())
884 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 4)
886 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0),
887 theIndices->Index (aVert + 1),
888 theIndices->Index (aVert + 2),
890 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0),
891 theIndices->Index (aVert + 2),
892 theIndices->Index (aVert + 3),
898 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 4)
900 theSet.Elements.push_back (BVH_Vec4i (aVert + 0, aVert + 1, aVert + 2,
902 theSet.Elements.push_back (BVH_Vec4i (aVert + 0, aVert + 2, aVert + 3,
907 return Standard_True;
910 // =======================================================================
911 // function : addRaytraceQuadrangleStripArray
912 // purpose : Adds OpenGL quad strip array to ray-traced scene geometry
913 // =======================================================================
914 Standard_Boolean OpenGl_View::addRaytraceQuadrangleStripArray (OpenGl_TriangleSet& theSet,
915 const Standard_Integer theMatID,
916 const Standard_Integer theCount,
917 const Standard_Integer theOffset,
918 const Handle(Graphic3d_IndexBuffer)& theIndices)
922 return Standard_True;
925 theSet.Elements.reserve (theSet.Elements.size() + 2 * theCount - 6);
927 if (!theIndices.IsNull())
929 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 2)
931 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0),
932 theIndices->Index (aVert + 1),
933 theIndices->Index (aVert + 2),
936 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 1),
937 theIndices->Index (aVert + 3),
938 theIndices->Index (aVert + 2),
944 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 2)
946 theSet.Elements.push_back (BVH_Vec4i (aVert + 0,
951 theSet.Elements.push_back (BVH_Vec4i (aVert + 1,
958 return Standard_True;
961 // =======================================================================
962 // function : addRaytracePolygonArray
963 // purpose : Adds OpenGL polygon array to ray-traced scene geometry
964 // =======================================================================
965 Standard_Boolean OpenGl_View::addRaytracePolygonArray (OpenGl_TriangleSet& theSet,
966 const Standard_Integer theMatID,
967 const Standard_Integer theCount,
968 const Standard_Integer theOffset,
969 const Handle(Graphic3d_IndexBuffer)& theIndices)
973 return Standard_True;
976 theSet.Elements.reserve (theSet.Elements.size() + theCount - 2);
978 if (!theIndices.IsNull())
980 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
982 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (theOffset),
983 theIndices->Index (aVert + 1),
984 theIndices->Index (aVert + 2),
990 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
992 theSet.Elements.push_back (BVH_Vec4i (theOffset,
999 return Standard_True;
1002 const TCollection_AsciiString OpenGl_View::ShaderSource::EMPTY_PREFIX;
1004 // =======================================================================
1005 // function : Source
1006 // purpose : Returns shader source combined with prefix
1007 // =======================================================================
1008 TCollection_AsciiString OpenGl_View::ShaderSource::Source() const
1010 const TCollection_AsciiString aVersion = "#version 140";
1012 if (myPrefix.IsEmpty())
1014 return aVersion + "\n" + mySource;
1017 return aVersion + "\n" + myPrefix + "\n" + mySource;
1020 // =======================================================================
1021 // function : LoadFromFiles
1022 // purpose : Loads shader source from specified files
1023 // =======================================================================
1024 Standard_Boolean OpenGl_View::ShaderSource::LoadFromFiles (const TCollection_AsciiString* theFileNames,
1025 const TCollection_AsciiString& thePrefix)
1029 myPrefix = thePrefix;
1031 TCollection_AsciiString aMissingFiles;
1032 for (Standard_Integer anIndex = 0; !theFileNames[anIndex].IsEmpty(); ++anIndex)
1034 OSD_File aFile (theFileNames[anIndex]);
1037 aFile.Open (OSD_ReadOnly, OSD_Protection());
1039 if (!aFile.IsOpen())
1041 if (!aMissingFiles.IsEmpty())
1043 aMissingFiles += ", ";
1045 aMissingFiles += TCollection_AsciiString("'") + theFileNames[anIndex] + "'";
1048 else if (!aMissingFiles.IsEmpty())
1054 TCollection_AsciiString aSource;
1055 aFile.Read (aSource, (Standard_Integer) aFile.Size());
1056 if (!aSource.IsEmpty())
1058 mySource += TCollection_AsciiString ("\n") + aSource;
1063 if (!aMissingFiles.IsEmpty())
1065 myError = TCollection_AsciiString("Shader files ") + aMissingFiles + " are missing or inaccessible";
1066 return Standard_False;
1068 return Standard_True;
1071 // =======================================================================
1072 // function : LoadFromStrings
1074 // =======================================================================
1075 Standard_Boolean OpenGl_View::ShaderSource::LoadFromStrings (const TCollection_AsciiString* theStrings,
1076 const TCollection_AsciiString& thePrefix)
1080 myPrefix = thePrefix;
1082 for (Standard_Integer anIndex = 0; !theStrings[anIndex].IsEmpty(); ++anIndex)
1084 TCollection_AsciiString aSource = theStrings[anIndex];
1085 if (!aSource.IsEmpty())
1087 mySource += TCollection_AsciiString ("\n") + aSource;
1090 return Standard_True;
1093 // =======================================================================
1094 // function : generateShaderPrefix
1095 // purpose : Generates shader prefix based on current ray-tracing options
1096 // =======================================================================
1097 TCollection_AsciiString OpenGl_View::generateShaderPrefix (const Handle(OpenGl_Context)& theGlContext) const
1099 TCollection_AsciiString aPrefixString =
1100 TCollection_AsciiString ("#define STACK_SIZE ") + TCollection_AsciiString (myRaytraceParameters.StackSize) + "\n" +
1101 TCollection_AsciiString ("#define NB_BOUNCES ") + TCollection_AsciiString (myRaytraceParameters.NbBounces);
1103 if (myRaytraceParameters.TransparentShadows)
1105 aPrefixString += TCollection_AsciiString ("\n#define TRANSPARENT_SHADOWS");
1108 // If OpenGL driver supports bindless textures and texturing
1109 // is actually used, activate texturing in ray-tracing mode
1110 if (myRaytraceParameters.UseBindlessTextures && theGlContext->arbTexBindless != NULL)
1112 aPrefixString += TCollection_AsciiString ("\n#define USE_TEXTURES") +
1113 TCollection_AsciiString ("\n#define MAX_TEX_NUMBER ") + TCollection_AsciiString (OpenGl_RaytraceGeometry::MAX_TEX_NUMBER);
1116 if (myRaytraceParameters.GlobalIllumination) // path tracing activated
1118 aPrefixString += TCollection_AsciiString ("\n#define PATH_TRACING");
1120 if (myRaytraceParameters.AdaptiveScreenSampling) // adaptive screen sampling requested
1122 // to activate the feature we need OpenGL 4.4 and GL_NV_shader_atomic_float extension
1123 if (theGlContext->IsGlGreaterEqual (4, 4) && theGlContext->CheckExtension ("GL_NV_shader_atomic_float"))
1125 aPrefixString += TCollection_AsciiString ("\n#define ADAPTIVE_SAMPLING") +
1126 TCollection_AsciiString ("\n#define BLOCK_SIZE ") + TCollection_AsciiString (OpenGl_TileSampler::TileSize());
1131 return aPrefixString;
1134 // =======================================================================
1135 // function : safeFailBack
1136 // purpose : Performs safe exit when shaders initialization fails
1137 // =======================================================================
1138 Standard_Boolean OpenGl_View::safeFailBack (const TCollection_ExtendedString& theMessage,
1139 const Handle(OpenGl_Context)& theGlContext)
1141 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1142 GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, theMessage);
1144 myRaytraceInitStatus = OpenGl_RT_FAIL;
1146 releaseRaytraceResources (theGlContext);
1148 return Standard_False;
1151 // =======================================================================
1152 // function : initShader
1153 // purpose : Creates new shader object with specified source
1154 // =======================================================================
1155 Handle(OpenGl_ShaderObject) OpenGl_View::initShader (const GLenum theType,
1156 const ShaderSource& theSource,
1157 const Handle(OpenGl_Context)& theGlContext)
1159 Handle(OpenGl_ShaderObject) aShader = new OpenGl_ShaderObject (theType);
1161 if (!aShader->Create (theGlContext))
1163 const TCollection_ExtendedString aMessage = TCollection_ExtendedString ("Error: Failed to create ") +
1164 (theType == GL_VERTEX_SHADER ? "vertex" : "fragment") + " shader object";
1166 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1167 GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, aMessage);
1169 aShader->Release (theGlContext.operator->());
1171 return Handle(OpenGl_ShaderObject)();
1174 if (!aShader->LoadSource (theGlContext, theSource.Source()))
1176 const TCollection_ExtendedString aMessage = TCollection_ExtendedString ("Error: Failed to set ") +
1177 (theType == GL_VERTEX_SHADER ? "vertex" : "fragment") + " shader source";
1179 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1180 GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, aMessage);
1182 aShader->Release (theGlContext.operator->());
1184 return Handle(OpenGl_ShaderObject)();
1187 TCollection_AsciiString aBuildLog;
1189 if (!aShader->Compile (theGlContext))
1191 aShader->FetchInfoLog (theGlContext, aBuildLog);
1193 const TCollection_ExtendedString aMessage = TCollection_ExtendedString ("Error: Failed to compile ") +
1194 (theType == GL_VERTEX_SHADER ? "vertex" : "fragment") + " shader object:\n" + aBuildLog;
1196 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1197 GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, aMessage);
1199 aShader->Release (theGlContext.operator->());
1201 #ifdef RAY_TRACE_PRINT_INFO
1202 std::cout << "Shader build log:\n" << aBuildLog << "\n";
1205 return Handle(OpenGl_ShaderObject)();
1207 else if (theGlContext->caps->glslWarnings)
1209 aShader->FetchInfoLog (theGlContext, aBuildLog);
1211 if (!aBuildLog.IsEmpty() && !aBuildLog.IsEqual ("No errors.\n"))
1213 const TCollection_ExtendedString aMessage = TCollection_ExtendedString (theType == GL_VERTEX_SHADER ?
1214 "Vertex" : "Fragment") + " shader was compiled with following warnings:\n" + aBuildLog;
1216 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1217 GL_DEBUG_TYPE_PORTABILITY, 0, GL_DEBUG_SEVERITY_LOW, aMessage);
1220 #ifdef RAY_TRACE_PRINT_INFO
1221 std::cout << "Shader build log:\n" << aBuildLog << "\n";
1228 // =======================================================================
1229 // function : initProgram
1230 // purpose : Creates GLSL program from the given shader objects
1231 // =======================================================================
1232 Handle(OpenGl_ShaderProgram) OpenGl_View::initProgram (const Handle(OpenGl_Context)& theGlContext,
1233 const Handle(OpenGl_ShaderObject)& theVertShader,
1234 const Handle(OpenGl_ShaderObject)& theFragShader)
1236 Handle(OpenGl_ShaderProgram) aProgram = new OpenGl_ShaderProgram;
1238 if (!aProgram->Create (theGlContext))
1240 theVertShader->Release (theGlContext.operator->());
1242 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1243 GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, "Failed to create shader program");
1245 return Handle(OpenGl_ShaderProgram)();
1248 if (!aProgram->AttachShader (theGlContext, theVertShader)
1249 || !aProgram->AttachShader (theGlContext, theFragShader))
1251 theVertShader->Release (theGlContext.operator->());
1253 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1254 GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, "Failed to attach shader objects");
1256 return Handle(OpenGl_ShaderProgram)();
1259 aProgram->SetAttributeName (theGlContext, Graphic3d_TOA_POS, "occVertex");
1261 TCollection_AsciiString aLinkLog;
1263 if (!aProgram->Link (theGlContext))
1265 aProgram->FetchInfoLog (theGlContext, aLinkLog);
1267 const TCollection_ExtendedString aMessage = TCollection_ExtendedString (
1268 "Failed to link shader program:\n") + aLinkLog;
1270 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1271 GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, aMessage);
1273 return Handle(OpenGl_ShaderProgram)();
1275 else if (theGlContext->caps->glslWarnings)
1277 aProgram->FetchInfoLog (theGlContext, aLinkLog);
1278 if (!aLinkLog.IsEmpty() && !aLinkLog.IsEqual ("No errors.\n"))
1280 const TCollection_ExtendedString aMessage = TCollection_ExtendedString (
1281 "Shader program was linked with following warnings:\n") + aLinkLog;
1283 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1284 GL_DEBUG_TYPE_PORTABILITY, 0, GL_DEBUG_SEVERITY_LOW, aMessage);
1291 // =======================================================================
1292 // function : initRaytraceResources
1293 // purpose : Initializes OpenGL/GLSL shader programs
1294 // =======================================================================
1295 Standard_Boolean OpenGl_View::initRaytraceResources (const Handle(OpenGl_Context)& theGlContext)
1297 if (myRaytraceInitStatus == OpenGl_RT_FAIL)
1299 return Standard_False;
1302 Standard_Boolean aToRebuildShaders = Standard_False;
1304 if (myRenderParams.RebuildRayTracingShaders) // requires complete re-initialization
1306 myRaytraceInitStatus = OpenGl_RT_NONE;
1307 releaseRaytraceResources (theGlContext, Standard_True);
1308 myRenderParams.RebuildRayTracingShaders = Standard_False; // clear rebuilding flag
1311 if (myRaytraceInitStatus == OpenGl_RT_INIT)
1313 if (!myIsRaytraceDataValid)
1315 return Standard_True;
1318 const Standard_Integer aRequiredStackSize =
1319 myRaytraceGeometry.TopLevelTreeDepth() + myRaytraceGeometry.BotLevelTreeDepth();
1321 if (myRaytraceParameters.StackSize < aRequiredStackSize)
1323 myRaytraceParameters.StackSize = Max (aRequiredStackSize, THE_DEFAULT_STACK_SIZE);
1325 aToRebuildShaders = Standard_True;
1329 if (aRequiredStackSize < myRaytraceParameters.StackSize)
1331 if (myRaytraceParameters.StackSize > THE_DEFAULT_STACK_SIZE)
1333 myRaytraceParameters.StackSize = Max (aRequiredStackSize, THE_DEFAULT_STACK_SIZE);
1334 aToRebuildShaders = Standard_True;
1339 if (myRenderParams.RaytracingDepth != myRaytraceParameters.NbBounces)
1341 myRaytraceParameters.NbBounces = myRenderParams.RaytracingDepth;
1342 aToRebuildShaders = Standard_True;
1345 if (myRaytraceGeometry.HasTextures() != myRaytraceParameters.UseBindlessTextures)
1347 myRaytraceParameters.UseBindlessTextures = myRaytraceGeometry.HasTextures();
1348 aToRebuildShaders = Standard_True;
1351 if (myRenderParams.IsTransparentShadowEnabled != myRaytraceParameters.TransparentShadows)
1353 myRaytraceParameters.TransparentShadows = myRenderParams.IsTransparentShadowEnabled;
1354 aToRebuildShaders = Standard_True;
1357 if (myRenderParams.IsGlobalIlluminationEnabled != myRaytraceParameters.GlobalIllumination)
1359 myRaytraceParameters.GlobalIllumination = myRenderParams.IsGlobalIlluminationEnabled;
1360 aToRebuildShaders = Standard_True;
1363 if (myRenderParams.AdaptiveScreenSampling != myRaytraceParameters.AdaptiveScreenSampling)
1365 myRaytraceParameters.AdaptiveScreenSampling = myRenderParams.AdaptiveScreenSampling;
1366 if (myRenderParams.AdaptiveScreenSampling) // adaptive sampling was requested
1368 if (!theGlContext->HasRayTracingAdaptiveSampling())
1370 // disable the feature if it is not supported
1371 myRaytraceParameters.AdaptiveScreenSampling = myRenderParams.AdaptiveScreenSampling = Standard_False;
1372 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_PORTABILITY, 0, GL_DEBUG_SEVERITY_LOW,
1373 "Adaptive sampling not supported (OpenGL 4.4 or GL_NV_shader_atomic_float is missing)");
1377 aToRebuildShaders = Standard_True;
1380 if (aToRebuildShaders)
1382 // Reject accumulated frames
1385 // Environment map should be updated
1386 myToUpdateEnvironmentMap = Standard_True;
1388 const TCollection_AsciiString aPrefixString = generateShaderPrefix (theGlContext);
1390 #ifdef RAY_TRACE_PRINT_INFO
1391 std::cout << "GLSL prefix string:" << std::endl << aPrefixString << std::endl;
1394 myRaytraceShaderSource.SetPrefix (aPrefixString);
1395 myPostFSAAShaderSource.SetPrefix (aPrefixString);
1396 myOutImageShaderSource.SetPrefix (aPrefixString);
1398 if (!myRaytraceShader->LoadSource (theGlContext, myRaytraceShaderSource.Source())
1399 || !myPostFSAAShader->LoadSource (theGlContext, myPostFSAAShaderSource.Source())
1400 || !myOutImageShader->LoadSource (theGlContext, myOutImageShaderSource.Source()))
1402 return safeFailBack ("Failed to load source into ray-tracing fragment shaders", theGlContext);
1405 if (!myRaytraceShader->Compile (theGlContext)
1406 || !myPostFSAAShader->Compile (theGlContext)
1407 || !myOutImageShader->Compile (theGlContext))
1409 return safeFailBack ("Failed to compile ray-tracing fragment shaders", theGlContext);
1412 myRaytraceProgram->SetAttributeName (theGlContext, Graphic3d_TOA_POS, "occVertex");
1413 myPostFSAAProgram->SetAttributeName (theGlContext, Graphic3d_TOA_POS, "occVertex");
1414 myOutImageProgram->SetAttributeName (theGlContext, Graphic3d_TOA_POS, "occVertex");
1416 if (!myRaytraceProgram->Link (theGlContext)
1417 || !myPostFSAAProgram->Link (theGlContext)
1418 || !myOutImageProgram->Link (theGlContext))
1420 return safeFailBack ("Failed to initialize vertex attributes for ray-tracing program", theGlContext);
1425 if (myRaytraceInitStatus == OpenGl_RT_NONE)
1427 myAccumFrames = 0; // reject accumulated frames
1429 if (!theGlContext->IsGlGreaterEqual (3, 1))
1431 return safeFailBack ("Ray-tracing requires OpenGL 3.1 and higher", theGlContext);
1433 else if (!theGlContext->arbTboRGB32)
1435 return safeFailBack ("Ray-tracing requires OpenGL 4.0+ or GL_ARB_texture_buffer_object_rgb32 extension", theGlContext);
1437 else if (!theGlContext->arbFBOBlit)
1439 return safeFailBack ("Ray-tracing requires EXT_framebuffer_blit extension", theGlContext);
1442 myRaytraceParameters.NbBounces = myRenderParams.RaytracingDepth;
1444 const TCollection_AsciiString aShaderFolder = Graphic3d_ShaderProgram::ShadersFolder();
1445 if (myIsRaytraceDataValid)
1447 myRaytraceParameters.StackSize = Max (THE_DEFAULT_STACK_SIZE,
1448 myRaytraceGeometry.TopLevelTreeDepth() + myRaytraceGeometry.BotLevelTreeDepth());
1451 const TCollection_AsciiString aPrefixString = generateShaderPrefix (theGlContext);
1453 #ifdef RAY_TRACE_PRINT_INFO
1454 std::cout << "GLSL prefix string:" << std::endl << aPrefixString << std::endl;
1457 ShaderSource aBasicVertShaderSrc;
1459 if (!aShaderFolder.IsEmpty())
1461 const TCollection_AsciiString aFiles[] = { aShaderFolder + "/RaytraceBase.vs", "" };
1462 if (!aBasicVertShaderSrc.LoadFromFiles (aFiles))
1464 return safeFailBack (aBasicVertShaderSrc.ErrorDescription(), theGlContext);
1469 const TCollection_AsciiString aSrcShaders[] = { Shaders_RaytraceBase_vs, "" };
1470 aBasicVertShaderSrc.LoadFromStrings (aSrcShaders);
1475 if (!aShaderFolder.IsEmpty())
1477 const TCollection_AsciiString aFiles[] = { aShaderFolder + "/RaytraceBase.fs",
1478 aShaderFolder + "/PathtraceBase.fs",
1479 aShaderFolder + "/RaytraceRender.fs",
1481 if (!myRaytraceShaderSource.LoadFromFiles (aFiles, aPrefixString))
1483 return safeFailBack (myRaytraceShaderSource.ErrorDescription(), theGlContext);
1488 const TCollection_AsciiString aSrcShaders[] = { Shaders_RaytraceBase_fs,
1489 Shaders_PathtraceBase_fs,
1490 Shaders_RaytraceRender_fs,
1492 myRaytraceShaderSource.LoadFromStrings (aSrcShaders, aPrefixString);
1495 Handle(OpenGl_ShaderObject) aBasicVertShader = initShader (GL_VERTEX_SHADER, aBasicVertShaderSrc, theGlContext);
1496 if (aBasicVertShader.IsNull())
1498 return safeFailBack ("Failed to initialize ray-trace vertex shader", theGlContext);
1501 myRaytraceShader = initShader (GL_FRAGMENT_SHADER, myRaytraceShaderSource, theGlContext);
1502 if (myRaytraceShader.IsNull())
1504 aBasicVertShader->Release (theGlContext.operator->());
1505 return safeFailBack ("Failed to initialize ray-trace fragment shader", theGlContext);
1508 myRaytraceProgram = initProgram (theGlContext, aBasicVertShader, myRaytraceShader);
1509 if (myRaytraceProgram.IsNull())
1511 return safeFailBack ("Failed to initialize ray-trace shader program", theGlContext);
1516 if (!aShaderFolder.IsEmpty())
1518 const TCollection_AsciiString aFiles[] = { aShaderFolder + "/RaytraceBase.fs", aShaderFolder + "/RaytraceSmooth.fs", "" };
1519 if (!myPostFSAAShaderSource.LoadFromFiles (aFiles, aPrefixString))
1521 return safeFailBack (myPostFSAAShaderSource.ErrorDescription(), theGlContext);
1526 const TCollection_AsciiString aSrcShaders[] = { Shaders_RaytraceBase_fs, Shaders_RaytraceSmooth_fs, "" };
1527 myPostFSAAShaderSource.LoadFromStrings (aSrcShaders, aPrefixString);
1530 Handle(OpenGl_ShaderObject) aBasicVertShader = initShader (GL_VERTEX_SHADER, aBasicVertShaderSrc, theGlContext);
1531 if (aBasicVertShader.IsNull())
1533 return safeFailBack ("Failed to initialize FSAA vertex shader", theGlContext);
1536 myPostFSAAShader = initShader (GL_FRAGMENT_SHADER, myPostFSAAShaderSource, theGlContext);
1537 if (myPostFSAAShader.IsNull())
1539 aBasicVertShader->Release (theGlContext.operator->());
1540 return safeFailBack ("Failed to initialize FSAA fragment shader", theGlContext);
1543 myPostFSAAProgram = initProgram (theGlContext, aBasicVertShader, myPostFSAAShader);
1544 if (myPostFSAAProgram.IsNull())
1546 return safeFailBack ("Failed to initialize FSAA shader program", theGlContext);
1551 if (!aShaderFolder.IsEmpty())
1553 const TCollection_AsciiString aFiles[] = { aShaderFolder + "/Display.fs", "" };
1554 if (!myOutImageShaderSource.LoadFromFiles (aFiles, aPrefixString))
1556 return safeFailBack (myOutImageShaderSource.ErrorDescription(), theGlContext);
1561 const TCollection_AsciiString aSrcShaders[] = { Shaders_Display_fs, "" };
1562 myOutImageShaderSource.LoadFromStrings (aSrcShaders, aPrefixString);
1565 Handle(OpenGl_ShaderObject) aBasicVertShader = initShader (GL_VERTEX_SHADER, aBasicVertShaderSrc, theGlContext);
1566 if (aBasicVertShader.IsNull())
1568 return safeFailBack ("Failed to set vertex shader source", theGlContext);
1571 myOutImageShader = initShader (GL_FRAGMENT_SHADER, myOutImageShaderSource, theGlContext);
1572 if (myOutImageShader.IsNull())
1574 aBasicVertShader->Release (theGlContext.operator->());
1575 return safeFailBack ("Failed to set display fragment shader source", theGlContext);
1578 myOutImageProgram = initProgram (theGlContext, aBasicVertShader, myOutImageShader);
1579 if (myOutImageProgram.IsNull())
1581 return safeFailBack ("Failed to initialize display shader program", theGlContext);
1586 if (myRaytraceInitStatus == OpenGl_RT_NONE || aToRebuildShaders)
1588 for (Standard_Integer anIndex = 0; anIndex < 2; ++anIndex)
1590 Handle(OpenGl_ShaderProgram)& aShaderProgram =
1591 (anIndex == 0) ? myRaytraceProgram : myPostFSAAProgram;
1593 theGlContext->BindProgram (aShaderProgram);
1595 aShaderProgram->SetSampler (theGlContext,
1596 "uSceneMinPointTexture", OpenGl_RT_SceneMinPointTexture);
1597 aShaderProgram->SetSampler (theGlContext,
1598 "uSceneMaxPointTexture", OpenGl_RT_SceneMaxPointTexture);
1599 aShaderProgram->SetSampler (theGlContext,
1600 "uSceneNodeInfoTexture", OpenGl_RT_SceneNodeInfoTexture);
1601 aShaderProgram->SetSampler (theGlContext,
1602 "uGeometryVertexTexture", OpenGl_RT_GeometryVertexTexture);
1603 aShaderProgram->SetSampler (theGlContext,
1604 "uGeometryNormalTexture", OpenGl_RT_GeometryNormalTexture);
1605 aShaderProgram->SetSampler (theGlContext,
1606 "uGeometryTexCrdTexture", OpenGl_RT_GeometryTexCrdTexture);
1607 aShaderProgram->SetSampler (theGlContext,
1608 "uGeometryTriangTexture", OpenGl_RT_GeometryTriangTexture);
1609 aShaderProgram->SetSampler (theGlContext,
1610 "uSceneTransformTexture", OpenGl_RT_SceneTransformTexture);
1611 aShaderProgram->SetSampler (theGlContext,
1612 "uEnvironmentMapTexture", OpenGl_RT_EnvironmentMapTexture);
1613 aShaderProgram->SetSampler (theGlContext,
1614 "uRaytraceMaterialTexture", OpenGl_RT_RaytraceMaterialTexture);
1615 aShaderProgram->SetSampler (theGlContext,
1616 "uRaytraceLightSrcTexture", OpenGl_RT_RaytraceLightSrcTexture);
1620 aShaderProgram->SetSampler (theGlContext,
1621 "uFSAAInputTexture", OpenGl_RT_FsaaInputTexture);
1625 aShaderProgram->SetSampler (theGlContext,
1626 "uAccumTexture", OpenGl_RT_PrevAccumTexture);
1629 myUniformLocations[anIndex][OpenGl_RT_aPosition] =
1630 aShaderProgram->GetAttributeLocation (theGlContext, "occVertex");
1632 myUniformLocations[anIndex][OpenGl_RT_uOriginLB] =
1633 aShaderProgram->GetUniformLocation (theGlContext, "uOriginLB");
1634 myUniformLocations[anIndex][OpenGl_RT_uOriginRB] =
1635 aShaderProgram->GetUniformLocation (theGlContext, "uOriginRB");
1636 myUniformLocations[anIndex][OpenGl_RT_uOriginLT] =
1637 aShaderProgram->GetUniformLocation (theGlContext, "uOriginLT");
1638 myUniformLocations[anIndex][OpenGl_RT_uOriginRT] =
1639 aShaderProgram->GetUniformLocation (theGlContext, "uOriginRT");
1640 myUniformLocations[anIndex][OpenGl_RT_uDirectLB] =
1641 aShaderProgram->GetUniformLocation (theGlContext, "uDirectLB");
1642 myUniformLocations[anIndex][OpenGl_RT_uDirectRB] =
1643 aShaderProgram->GetUniformLocation (theGlContext, "uDirectRB");
1644 myUniformLocations[anIndex][OpenGl_RT_uDirectLT] =
1645 aShaderProgram->GetUniformLocation (theGlContext, "uDirectLT");
1646 myUniformLocations[anIndex][OpenGl_RT_uDirectRT] =
1647 aShaderProgram->GetUniformLocation (theGlContext, "uDirectRT");
1648 myUniformLocations[anIndex][OpenGl_RT_uViewPrMat] =
1649 aShaderProgram->GetUniformLocation (theGlContext, "uViewMat");
1650 myUniformLocations[anIndex][OpenGl_RT_uUnviewMat] =
1651 aShaderProgram->GetUniformLocation (theGlContext, "uUnviewMat");
1653 myUniformLocations[anIndex][OpenGl_RT_uSceneRad] =
1654 aShaderProgram->GetUniformLocation (theGlContext, "uSceneRadius");
1655 myUniformLocations[anIndex][OpenGl_RT_uSceneEps] =
1656 aShaderProgram->GetUniformLocation (theGlContext, "uSceneEpsilon");
1657 myUniformLocations[anIndex][OpenGl_RT_uLightCount] =
1658 aShaderProgram->GetUniformLocation (theGlContext, "uLightCount");
1659 myUniformLocations[anIndex][OpenGl_RT_uLightAmbnt] =
1660 aShaderProgram->GetUniformLocation (theGlContext, "uGlobalAmbient");
1662 myUniformLocations[anIndex][OpenGl_RT_uOffsetX] =
1663 aShaderProgram->GetUniformLocation (theGlContext, "uOffsetX");
1664 myUniformLocations[anIndex][OpenGl_RT_uOffsetY] =
1665 aShaderProgram->GetUniformLocation (theGlContext, "uOffsetY");
1666 myUniformLocations[anIndex][OpenGl_RT_uSamples] =
1667 aShaderProgram->GetUniformLocation (theGlContext, "uSamples");
1669 myUniformLocations[anIndex][OpenGl_RT_uTexSamplersArray] =
1670 aShaderProgram->GetUniformLocation (theGlContext, "uTextureSamplers");
1672 myUniformLocations[anIndex][OpenGl_RT_uShadowsEnabled] =
1673 aShaderProgram->GetUniformLocation (theGlContext, "uShadowsEnabled");
1674 myUniformLocations[anIndex][OpenGl_RT_uReflectEnabled] =
1675 aShaderProgram->GetUniformLocation (theGlContext, "uReflectEnabled");
1676 myUniformLocations[anIndex][OpenGl_RT_uSphereMapEnabled] =
1677 aShaderProgram->GetUniformLocation (theGlContext, "uSphereMapEnabled");
1678 myUniformLocations[anIndex][OpenGl_RT_uSphereMapForBack] =
1679 aShaderProgram->GetUniformLocation (theGlContext, "uSphereMapForBack");
1680 myUniformLocations[anIndex][OpenGl_RT_uBlockedRngEnabled] =
1681 aShaderProgram->GetUniformLocation (theGlContext, "uBlockedRngEnabled");
1683 myUniformLocations[anIndex][OpenGl_RT_uWinSizeX] =
1684 aShaderProgram->GetUniformLocation (theGlContext, "uWinSizeX");
1685 myUniformLocations[anIndex][OpenGl_RT_uWinSizeY] =
1686 aShaderProgram->GetUniformLocation (theGlContext, "uWinSizeY");
1688 myUniformLocations[anIndex][OpenGl_RT_uSampleWeight] =
1689 aShaderProgram->GetUniformLocation (theGlContext, "uSampleWeight");
1690 myUniformLocations[anIndex][OpenGl_RT_uFrameRndSeed] =
1691 aShaderProgram->GetUniformLocation (theGlContext, "uFrameRndSeed");
1693 myUniformLocations[anIndex][OpenGl_RT_uRenderImage] =
1694 aShaderProgram->GetUniformLocation (theGlContext, "uRenderImage");
1695 myUniformLocations[anIndex][OpenGl_RT_uOffsetImage] =
1696 aShaderProgram->GetUniformLocation (theGlContext, "uOffsetImage");
1698 myUniformLocations[anIndex][OpenGl_RT_uBackColorTop] =
1699 aShaderProgram->GetUniformLocation (theGlContext, "uBackColorTop");
1700 myUniformLocations[anIndex][OpenGl_RT_uBackColorBot] =
1701 aShaderProgram->GetUniformLocation (theGlContext, "uBackColorBot");
1704 theGlContext->BindProgram (myOutImageProgram);
1706 myOutImageProgram->SetSampler (theGlContext,
1707 "uInputTexture", OpenGl_RT_PrevAccumTexture);
1709 myOutImageProgram->SetSampler (theGlContext,
1710 "uDepthTexture", OpenGl_RT_RaytraceDepthTexture);
1712 theGlContext->BindProgram (NULL);
1715 if (myRaytraceInitStatus != OpenGl_RT_NONE)
1717 return myRaytraceInitStatus == OpenGl_RT_INIT;
1720 const GLfloat aVertices[] = { -1.f, -1.f, 0.f,
1727 myRaytraceScreenQuad.Init (theGlContext, 3, 6, aVertices);
1729 myRaytraceInitStatus = OpenGl_RT_INIT; // initialized in normal way
1731 return Standard_True;
1734 // =======================================================================
1735 // function : nullifyResource
1736 // purpose : Releases OpenGL resource
1737 // =======================================================================
1739 inline void nullifyResource (const Handle(OpenGl_Context)& theGlContext, Handle(T)& theResource)
1741 if (!theResource.IsNull())
1743 theResource->Release (theGlContext.operator->());
1744 theResource.Nullify();
1748 // =======================================================================
1749 // function : releaseRaytraceResources
1750 // purpose : Releases OpenGL/GLSL shader programs
1751 // =======================================================================
1752 void OpenGl_View::releaseRaytraceResources (const Handle(OpenGl_Context)& theGlContext, const Standard_Boolean theToRebuild)
1754 // release shader resources
1755 nullifyResource (theGlContext, myRaytraceShader);
1756 nullifyResource (theGlContext, myPostFSAAShader);
1758 nullifyResource (theGlContext, myRaytraceProgram);
1759 nullifyResource (theGlContext, myPostFSAAProgram);
1760 nullifyResource (theGlContext, myOutImageProgram);
1762 if (!theToRebuild) // complete release
1764 myRaytraceFBO1[0]->Release (theGlContext.operator->());
1765 myRaytraceFBO1[1]->Release (theGlContext.operator->());
1766 myRaytraceFBO2[0]->Release (theGlContext.operator->());
1767 myRaytraceFBO2[1]->Release (theGlContext.operator->());
1769 nullifyResource (theGlContext, myRaytraceOutputTexture[0]);
1770 nullifyResource (theGlContext, myRaytraceOutputTexture[1]);
1772 nullifyResource (theGlContext, myRaytraceTileOffsetsTexture);
1773 nullifyResource (theGlContext, myRaytraceVisualErrorTexture);
1775 nullifyResource (theGlContext, mySceneNodeInfoTexture);
1776 nullifyResource (theGlContext, mySceneMinPointTexture);
1777 nullifyResource (theGlContext, mySceneMaxPointTexture);
1779 nullifyResource (theGlContext, myGeometryVertexTexture);
1780 nullifyResource (theGlContext, myGeometryNormalTexture);
1781 nullifyResource (theGlContext, myGeometryTexCrdTexture);
1782 nullifyResource (theGlContext, myGeometryTriangTexture);
1783 nullifyResource (theGlContext, mySceneTransformTexture);
1785 nullifyResource (theGlContext, myRaytraceLightSrcTexture);
1786 nullifyResource (theGlContext, myRaytraceMaterialTexture);
1788 myRaytraceGeometry.ReleaseResources (theGlContext);
1790 if (myRaytraceScreenQuad.IsValid ())
1792 myRaytraceScreenQuad.Release (theGlContext.operator->());
1797 // =======================================================================
1798 // function : updateRaytraceBuffers
1799 // purpose : Updates auxiliary OpenGL frame buffers.
1800 // =======================================================================
1801 Standard_Boolean OpenGl_View::updateRaytraceBuffers (const Standard_Integer theSizeX,
1802 const Standard_Integer theSizeY,
1803 const Handle(OpenGl_Context)& theGlContext)
1805 // Auxiliary buffers are not used.
1806 if (!myRaytraceParameters.GlobalIllumination && !myRenderParams.IsAntialiasingEnabled)
1808 myRaytraceFBO1[0]->Release (theGlContext.operator->());
1809 myRaytraceFBO2[0]->Release (theGlContext.operator->());
1810 myRaytraceFBO1[1]->Release (theGlContext.operator->());
1811 myRaytraceFBO2[1]->Release (theGlContext.operator->());
1813 return Standard_True;
1816 myRaytraceFBO1[0]->InitLazy (theGlContext, theSizeX, theSizeY, GL_RGBA32F, myFboDepthFormat);
1817 myRaytraceFBO2[0]->InitLazy (theGlContext, theSizeX, theSizeY, GL_RGBA32F, myFboDepthFormat);
1819 // Init second set of buffers for stereographic rendering.
1820 if (myCamera->ProjectionType() == Graphic3d_Camera::Projection_Stereo)
1822 myRaytraceFBO1[1]->InitLazy (theGlContext, theSizeX, theSizeY, GL_RGBA32F, myFboDepthFormat);
1823 myRaytraceFBO2[1]->InitLazy (theGlContext, theSizeX, theSizeY, GL_RGBA32F, myFboDepthFormat);
1827 myRaytraceFBO1[1]->Release (theGlContext.operator->());
1828 myRaytraceFBO2[1]->Release (theGlContext.operator->());
1831 myTileSampler.SetSize (theSizeX, theSizeY);
1833 if (myRaytraceTileOffsetsTexture.IsNull())
1835 myRaytraceOutputTexture[0] = new OpenGl_Texture();
1836 myRaytraceOutputTexture[1] = new OpenGl_Texture();
1838 myRaytraceTileOffsetsTexture = new OpenGl_Texture();
1839 myRaytraceVisualErrorTexture = new OpenGl_Texture();
1842 if (myRaytraceOutputTexture[0]->SizeX() / 3 != theSizeX
1843 || myRaytraceOutputTexture[0]->SizeY() / 2 != theSizeY)
1845 // Due to limitations of OpenGL image load-store extension
1846 // atomic operations are supported only for single-channel
1847 // images, so we define GL_R32F image. It is used as array
1848 // of 6D floating point vectors:
1849 // 0 - R color channel
1850 // 1 - G color channel
1851 // 2 - B color channel
1852 // 3 - hit time transformed into OpenGL NDC space
1853 // 4 - luminance accumulated for odd samples only
1854 myRaytraceOutputTexture[0]->InitRectangle (theGlContext,
1855 theSizeX * 3, theSizeY * 2, OpenGl_TextureFormat::Create<GLfloat, 1>());
1857 myRaytraceVisualErrorTexture->Init (theGlContext,
1858 GL_R32I, GL_RED_INTEGER, GL_INT, myTileSampler.NbTilesX(), myTileSampler.NbTilesY(), Graphic3d_TOT_2D);
1860 myRaytraceTileOffsetsTexture->Init (theGlContext,
1861 GL_RG32I, GL_RG_INTEGER, GL_INT, myTileSampler.NbTilesX(), myTileSampler.NbTilesY(), Graphic3d_TOT_2D);
1864 if (myCamera->ProjectionType() == Graphic3d_Camera::Projection_Stereo)
1866 if (myRaytraceOutputTexture[1]->SizeX() / 3 != theSizeX
1867 || myRaytraceOutputTexture[1]->SizeY() / 2 != theSizeY)
1869 myRaytraceOutputTexture[1]->InitRectangle (theGlContext,
1870 theSizeX * 3, theSizeY * 2, OpenGl_TextureFormat::Create<GLfloat, 1>());
1875 myRaytraceOutputTexture[1]->Release (theGlContext.operator->());
1878 return Standard_True;
1881 // =======================================================================
1882 // function : updateCamera
1883 // purpose : Generates viewing rays for corners of screen quad
1884 // =======================================================================
1885 void OpenGl_View::updateCamera (const OpenGl_Mat4& theOrientation,
1886 const OpenGl_Mat4& theViewMapping,
1887 OpenGl_Vec3* theOrigins,
1888 OpenGl_Vec3* theDirects,
1889 OpenGl_Mat4& theViewPr,
1890 OpenGl_Mat4& theUnview)
1892 // compute view-projection matrix
1893 theViewPr = theViewMapping * theOrientation;
1895 // compute inverse view-projection matrix
1896 theViewPr.Inverted (theUnview);
1898 Standard_Integer aOriginIndex = 0;
1899 Standard_Integer aDirectIndex = 0;
1901 for (Standard_Integer aY = -1; aY <= 1; aY += 2)
1903 for (Standard_Integer aX = -1; aX <= 1; aX += 2)
1905 OpenGl_Vec4 aOrigin (GLfloat(aX),
1910 aOrigin = theUnview * aOrigin;
1912 aOrigin.x() = aOrigin.x() / aOrigin.w();
1913 aOrigin.y() = aOrigin.y() / aOrigin.w();
1914 aOrigin.z() = aOrigin.z() / aOrigin.w();
1916 OpenGl_Vec4 aDirect (GLfloat(aX),
1921 aDirect = theUnview * aDirect;
1923 aDirect.x() = aDirect.x() / aDirect.w();
1924 aDirect.y() = aDirect.y() / aDirect.w();
1925 aDirect.z() = aDirect.z() / aDirect.w();
1927 aDirect = aDirect - aOrigin;
1929 theOrigins[aOriginIndex++] = OpenGl_Vec3 (static_cast<GLfloat> (aOrigin.x()),
1930 static_cast<GLfloat> (aOrigin.y()),
1931 static_cast<GLfloat> (aOrigin.z()));
1933 theDirects[aDirectIndex++] = OpenGl_Vec3 (static_cast<GLfloat> (aDirect.x()),
1934 static_cast<GLfloat> (aDirect.y()),
1935 static_cast<GLfloat> (aDirect.z()));
1940 // =======================================================================
1941 // function : uploadRaytraceData
1942 // purpose : Uploads ray-trace data to the GPU
1943 // =======================================================================
1944 Standard_Boolean OpenGl_View::uploadRaytraceData (const Handle(OpenGl_Context)& theGlContext)
1946 if (!theGlContext->IsGlGreaterEqual (3, 1))
1948 #ifdef RAY_TRACE_PRINT_INFO
1949 std::cout << "Error: OpenGL version is less than 3.1" << std::endl;
1951 return Standard_False;
1954 myAccumFrames = 0; // accumulation should be restarted
1956 /////////////////////////////////////////////////////////////////////////////
1957 // Prepare OpenGL textures
1959 if (theGlContext->arbTexBindless != NULL)
1961 // If OpenGL driver supports bindless textures we need
1962 // to get unique 64- bit handles for using on the GPU
1963 if (!myRaytraceGeometry.UpdateTextureHandles (theGlContext))
1965 #ifdef RAY_TRACE_PRINT_INFO
1966 std::cout << "Error: Failed to get OpenGL texture handles" << std::endl;
1968 return Standard_False;
1972 /////////////////////////////////////////////////////////////////////////////
1973 // Create OpenGL BVH buffers
1975 if (mySceneNodeInfoTexture.IsNull()) // create scene BVH buffers
1977 mySceneNodeInfoTexture = new OpenGl_TextureBufferArb;
1978 mySceneMinPointTexture = new OpenGl_TextureBufferArb;
1979 mySceneMaxPointTexture = new OpenGl_TextureBufferArb;
1980 mySceneTransformTexture = new OpenGl_TextureBufferArb;
1982 if (!mySceneNodeInfoTexture->Create (theGlContext)
1983 || !mySceneMinPointTexture->Create (theGlContext)
1984 || !mySceneMaxPointTexture->Create (theGlContext)
1985 || !mySceneTransformTexture->Create (theGlContext))
1987 #ifdef RAY_TRACE_PRINT_INFO
1988 std::cout << "Error: Failed to create scene BVH buffers" << std::endl;
1990 return Standard_False;
1994 if (myGeometryVertexTexture.IsNull()) // create geometry buffers
1996 myGeometryVertexTexture = new OpenGl_TextureBufferArb;
1997 myGeometryNormalTexture = new OpenGl_TextureBufferArb;
1998 myGeometryTexCrdTexture = new OpenGl_TextureBufferArb;
1999 myGeometryTriangTexture = new OpenGl_TextureBufferArb;
2001 if (!myGeometryVertexTexture->Create (theGlContext)
2002 || !myGeometryNormalTexture->Create (theGlContext)
2003 || !myGeometryTexCrdTexture->Create (theGlContext)
2004 || !myGeometryTriangTexture->Create (theGlContext))
2006 #ifdef RAY_TRACE_PRINT_INFO
2007 std::cout << "Error: Failed to create buffers for triangulation data" << std::endl;
2009 return Standard_False;
2013 if (myRaytraceMaterialTexture.IsNull()) // create material buffer
2015 myRaytraceMaterialTexture = new OpenGl_TextureBufferArb;
2017 if (!myRaytraceMaterialTexture->Create (theGlContext))
2019 #ifdef RAY_TRACE_PRINT_INFO
2020 std::cout << "Error: Failed to create buffers for material data" << std::endl;
2022 return Standard_False;
2026 /////////////////////////////////////////////////////////////////////////////
2027 // Write transform buffer
2029 BVH_Mat4f* aNodeTransforms = new BVH_Mat4f[myRaytraceGeometry.Size()];
2031 bool aResult = true;
2033 for (Standard_Integer anElemIndex = 0; anElemIndex < myRaytraceGeometry.Size(); ++anElemIndex)
2035 OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
2036 myRaytraceGeometry.Objects().ChangeValue (anElemIndex).operator->());
2038 const BVH_Transform<Standard_ShortReal, 4>* aTransform =
2039 dynamic_cast<const BVH_Transform<Standard_ShortReal, 4>* > (aTriangleSet->Properties().operator->());
2041 Standard_ASSERT_RETURN (aTransform != NULL,
2042 "OpenGl_TriangleSet does not contain transform", Standard_False);
2044 aNodeTransforms[anElemIndex] = aTransform->Inversed();
2047 aResult &= mySceneTransformTexture->Init (theGlContext, 4,
2048 myRaytraceGeometry.Size() * 4, reinterpret_cast<const GLfloat*> (aNodeTransforms));
2050 delete [] aNodeTransforms;
2052 /////////////////////////////////////////////////////////////////////////////
2053 // Write geometry and bottom-level BVH buffers
2055 Standard_Size aTotalVerticesNb = 0;
2056 Standard_Size aTotalElementsNb = 0;
2057 Standard_Size aTotalBVHNodesNb = 0;
2059 for (Standard_Integer anElemIndex = 0; anElemIndex < myRaytraceGeometry.Size(); ++anElemIndex)
2061 OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
2062 myRaytraceGeometry.Objects().ChangeValue (anElemIndex).operator->());
2064 Standard_ASSERT_RETURN (aTriangleSet != NULL,
2065 "Error: Failed to get triangulation of OpenGL element", Standard_False);
2067 aTotalVerticesNb += aTriangleSet->Vertices.size();
2068 aTotalElementsNb += aTriangleSet->Elements.size();
2070 Standard_ASSERT_RETURN (!aTriangleSet->QuadBVH().IsNull(),
2071 "Error: Failed to get bottom-level BVH of OpenGL element", Standard_False);
2073 aTotalBVHNodesNb += aTriangleSet->QuadBVH()->NodeInfoBuffer().size();
2076 aTotalBVHNodesNb += myRaytraceGeometry.QuadBVH()->NodeInfoBuffer().size();
2078 if (aTotalBVHNodesNb != 0)
2080 aResult &= mySceneNodeInfoTexture->Init (
2081 theGlContext, 4, GLsizei (aTotalBVHNodesNb), static_cast<const GLuint*> (NULL));
2082 aResult &= mySceneMinPointTexture->Init (
2083 theGlContext, 3, GLsizei (aTotalBVHNodesNb), static_cast<const GLfloat*> (NULL));
2084 aResult &= mySceneMaxPointTexture->Init (
2085 theGlContext, 3, GLsizei (aTotalBVHNodesNb), static_cast<const GLfloat*> (NULL));
2090 #ifdef RAY_TRACE_PRINT_INFO
2091 std::cout << "Error: Failed to upload buffers for bottom-level scene BVH" << std::endl;
2093 return Standard_False;
2096 if (aTotalElementsNb != 0)
2098 aResult &= myGeometryTriangTexture->Init (
2099 theGlContext, 4, GLsizei (aTotalElementsNb), static_cast<const GLuint*> (NULL));
2102 if (aTotalVerticesNb != 0)
2104 aResult &= myGeometryVertexTexture->Init (
2105 theGlContext, 3, GLsizei (aTotalVerticesNb), static_cast<const GLfloat*> (NULL));
2106 aResult &= myGeometryNormalTexture->Init (
2107 theGlContext, 3, GLsizei (aTotalVerticesNb), static_cast<const GLfloat*> (NULL));
2108 aResult &= myGeometryTexCrdTexture->Init (
2109 theGlContext, 2, GLsizei (aTotalVerticesNb), static_cast<const GLfloat*> (NULL));
2114 #ifdef RAY_TRACE_PRINT_INFO
2115 std::cout << "Error: Failed to upload buffers for scene geometry" << std::endl;
2117 return Standard_False;
2120 const QuadBvhHandle& aBVH = myRaytraceGeometry.QuadBVH();
2122 if (aBVH->Length() > 0)
2124 aResult &= mySceneNodeInfoTexture->SubData (theGlContext, 0, aBVH->Length(),
2125 reinterpret_cast<const GLuint*> (&aBVH->NodeInfoBuffer().front()));
2126 aResult &= mySceneMinPointTexture->SubData (theGlContext, 0, aBVH->Length(),
2127 reinterpret_cast<const GLfloat*> (&aBVH->MinPointBuffer().front()));
2128 aResult &= mySceneMaxPointTexture->SubData (theGlContext, 0, aBVH->Length(),
2129 reinterpret_cast<const GLfloat*> (&aBVH->MaxPointBuffer().front()));
2132 for (Standard_Integer aNodeIdx = 0; aNodeIdx < aBVH->Length(); ++aNodeIdx)
2134 if (!aBVH->IsOuter (aNodeIdx))
2137 OpenGl_TriangleSet* aTriangleSet = myRaytraceGeometry.TriangleSet (aNodeIdx);
2139 Standard_ASSERT_RETURN (aTriangleSet != NULL,
2140 "Error: Failed to get triangulation of OpenGL element", Standard_False);
2142 Standard_Integer aBVHOffset = myRaytraceGeometry.AccelerationOffset (aNodeIdx);
2144 Standard_ASSERT_RETURN (aBVHOffset != OpenGl_RaytraceGeometry::INVALID_OFFSET,
2145 "Error: Failed to get offset for bottom-level BVH", Standard_False);
2147 const Standard_Integer aBvhBuffersSize = aTriangleSet->QuadBVH()->Length();
2149 if (aBvhBuffersSize != 0)
2151 aResult &= mySceneNodeInfoTexture->SubData (theGlContext, aBVHOffset, aBvhBuffersSize,
2152 reinterpret_cast<const GLuint*> (&aTriangleSet->QuadBVH()->NodeInfoBuffer().front()));
2153 aResult &= mySceneMinPointTexture->SubData (theGlContext, aBVHOffset, aBvhBuffersSize,
2154 reinterpret_cast<const GLfloat*> (&aTriangleSet->QuadBVH()->MinPointBuffer().front()));
2155 aResult &= mySceneMaxPointTexture->SubData (theGlContext, aBVHOffset, aBvhBuffersSize,
2156 reinterpret_cast<const GLfloat*> (&aTriangleSet->QuadBVH()->MaxPointBuffer().front()));
2160 #ifdef RAY_TRACE_PRINT_INFO
2161 std::cout << "Error: Failed to upload buffers for bottom-level scene BVHs" << std::endl;
2163 return Standard_False;
2167 const Standard_Integer aVerticesOffset = myRaytraceGeometry.VerticesOffset (aNodeIdx);
2169 Standard_ASSERT_RETURN (aVerticesOffset != OpenGl_RaytraceGeometry::INVALID_OFFSET,
2170 "Error: Failed to get offset for triangulation vertices of OpenGL element", Standard_False);
2172 if (!aTriangleSet->Vertices.empty())
2174 aResult &= myGeometryNormalTexture->SubData (theGlContext, aVerticesOffset,
2175 GLsizei (aTriangleSet->Normals.size()), reinterpret_cast<const GLfloat*> (&aTriangleSet->Normals.front()));
2176 aResult &= myGeometryTexCrdTexture->SubData (theGlContext, aVerticesOffset,
2177 GLsizei (aTriangleSet->TexCrds.size()), reinterpret_cast<const GLfloat*> (&aTriangleSet->TexCrds.front()));
2178 aResult &= myGeometryVertexTexture->SubData (theGlContext, aVerticesOffset,
2179 GLsizei (aTriangleSet->Vertices.size()), reinterpret_cast<const GLfloat*> (&aTriangleSet->Vertices.front()));
2182 const Standard_Integer anElementsOffset = myRaytraceGeometry.ElementsOffset (aNodeIdx);
2184 Standard_ASSERT_RETURN (anElementsOffset != OpenGl_RaytraceGeometry::INVALID_OFFSET,
2185 "Error: Failed to get offset for triangulation elements of OpenGL element", Standard_False);
2187 if (!aTriangleSet->Elements.empty())
2189 aResult &= myGeometryTriangTexture->SubData (theGlContext, anElementsOffset, GLsizei (aTriangleSet->Elements.size()),
2190 reinterpret_cast<const GLuint*> (&aTriangleSet->Elements.front()));
2195 #ifdef RAY_TRACE_PRINT_INFO
2196 std::cout << "Error: Failed to upload triangulation buffers for OpenGL element" << std::endl;
2198 return Standard_False;
2202 /////////////////////////////////////////////////////////////////////////////
2203 // Write material buffer
2205 if (myRaytraceGeometry.Materials.size() != 0)
2207 aResult &= myRaytraceMaterialTexture->Init (theGlContext, 4,
2208 GLsizei (myRaytraceGeometry.Materials.size() * 18), myRaytraceGeometry.Materials.front().Packed());
2212 #ifdef RAY_TRACE_PRINT_INFO
2213 std::cout << "Error: Failed to upload material buffer" << std::endl;
2215 return Standard_False;
2219 myIsRaytraceDataValid = myRaytraceGeometry.Objects().Size() != 0;
2221 #ifdef RAY_TRACE_PRINT_INFO
2223 Standard_ShortReal aMemTrgUsed = 0.f;
2224 Standard_ShortReal aMemBvhUsed = 0.f;
2226 for (Standard_Integer anElemIdx = 0; anElemIdx < myRaytraceGeometry.Size(); ++anElemIdx)
2228 OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (myRaytraceGeometry.Objects()(anElemIdx).get());
2230 aMemTrgUsed += static_cast<Standard_ShortReal> (
2231 aTriangleSet->Vertices.size() * sizeof (BVH_Vec3f));
2232 aMemTrgUsed += static_cast<Standard_ShortReal> (
2233 aTriangleSet->Normals.size() * sizeof (BVH_Vec3f));
2234 aMemTrgUsed += static_cast<Standard_ShortReal> (
2235 aTriangleSet->TexCrds.size() * sizeof (BVH_Vec2f));
2236 aMemTrgUsed += static_cast<Standard_ShortReal> (
2237 aTriangleSet->Elements.size() * sizeof (BVH_Vec4i));
2239 aMemBvhUsed += static_cast<Standard_ShortReal> (
2240 aTriangleSet->QuadBVH()->NodeInfoBuffer().size() * sizeof (BVH_Vec4i));
2241 aMemBvhUsed += static_cast<Standard_ShortReal> (
2242 aTriangleSet->QuadBVH()->MinPointBuffer().size() * sizeof (BVH_Vec3f));
2243 aMemBvhUsed += static_cast<Standard_ShortReal> (
2244 aTriangleSet->QuadBVH()->MaxPointBuffer().size() * sizeof (BVH_Vec3f));
2247 aMemBvhUsed += static_cast<Standard_ShortReal> (
2248 myRaytraceGeometry.QuadBVH()->NodeInfoBuffer().size() * sizeof (BVH_Vec4i));
2249 aMemBvhUsed += static_cast<Standard_ShortReal> (
2250 myRaytraceGeometry.QuadBVH()->MinPointBuffer().size() * sizeof (BVH_Vec3f));
2251 aMemBvhUsed += static_cast<Standard_ShortReal> (
2252 myRaytraceGeometry.QuadBVH()->MaxPointBuffer().size() * sizeof (BVH_Vec3f));
2254 std::cout << "GPU Memory Used (Mb):\n"
2255 << "\tFor mesh: " << aMemTrgUsed / 1048576 << "\n"
2256 << "\tFor BVHs: " << aMemBvhUsed / 1048576 << "\n";
2263 // =======================================================================
2264 // function : updateRaytraceLightSources
2265 // purpose : Updates 3D scene light sources for ray-tracing
2266 // =======================================================================
2267 Standard_Boolean OpenGl_View::updateRaytraceLightSources (const OpenGl_Mat4& theInvModelView, const Handle(OpenGl_Context)& theGlContext)
2269 myRaytraceGeometry.Sources.clear();
2271 myRaytraceGeometry.Ambient = BVH_Vec4f (0.0f, 0.0f, 0.0f, 0.0f);
2273 OpenGl_ListOfLight::Iterator aLightIter (myShadingModel == Graphic3d_TOSM_NONE ? myNoShadingLight : myLights);
2274 for (; aLightIter.More(); aLightIter.Next())
2276 const OpenGl_Light& aLight = aLightIter.Value();
2278 if (aLight.Type == Graphic3d_TOLS_AMBIENT)
2280 myRaytraceGeometry.Ambient += BVH_Vec4f (aLight.Color.r() * aLight.Intensity,
2281 aLight.Color.g() * aLight.Intensity,
2282 aLight.Color.b() * aLight.Intensity,
2287 BVH_Vec4f aDiffuse (aLight.Color.r() * aLight.Intensity,
2288 aLight.Color.g() * aLight.Intensity,
2289 aLight.Color.b() * aLight.Intensity,
2292 BVH_Vec4f aPosition (-aLight.Direction.x(),
2293 -aLight.Direction.y(),
2294 -aLight.Direction.z(),
2297 if (aLight.Type != Graphic3d_TOLS_DIRECTIONAL)
2299 aPosition = BVH_Vec4f (static_cast<float>(aLight.Position.x()),
2300 static_cast<float>(aLight.Position.y()),
2301 static_cast<float>(aLight.Position.z()),
2304 // store smoothing radius in w-component
2305 aDiffuse.w() = Max (aLight.Smoothness, 0.f);
2309 // store cosine of smoothing angle in w-component
2310 aDiffuse.w() = cosf (Min (Max (aLight.Smoothness, 0.f), static_cast<Standard_ShortReal> (M_PI / 2.0)));
2313 if (aLight.IsHeadlight)
2315 aPosition = theInvModelView * aPosition;
2318 myRaytraceGeometry.Sources.push_back (OpenGl_RaytraceLight (aDiffuse, aPosition));
2321 if (myRaytraceLightSrcTexture.IsNull()) // create light source buffer
2323 myRaytraceLightSrcTexture = new OpenGl_TextureBufferArb;
2325 if (!myRaytraceLightSrcTexture->Create (theGlContext))
2327 #ifdef RAY_TRACE_PRINT_INFO
2328 std::cout << "Error: Failed to create light source buffer" << std::endl;
2330 return Standard_False;
2334 if (myRaytraceGeometry.Sources.size() != 0)
2336 const GLfloat* aDataPtr = myRaytraceGeometry.Sources.front().Packed();
2337 if (!myRaytraceLightSrcTexture->Init (theGlContext, 4, GLsizei (myRaytraceGeometry.Sources.size() * 2), aDataPtr))
2339 #ifdef RAY_TRACE_PRINT_INFO
2340 std::cout << "Error: Failed to upload light source buffer" << std::endl;
2342 return Standard_False;
2346 return Standard_True;
2349 // =======================================================================
2350 // function : updateRaytraceEnvironmentMap
2351 // purpose : Updates environment map for ray-tracing
2352 // =======================================================================
2353 Standard_Boolean OpenGl_View::updateRaytraceEnvironmentMap (const Handle(OpenGl_Context)& theGlContext)
2355 Standard_Boolean aResult = Standard_True;
2357 if (!myToUpdateEnvironmentMap)
2362 Handle(OpenGl_ShaderProgram) aPrograms[] = { myRaytraceProgram,
2363 myPostFSAAProgram };
2365 for (Standard_Integer anIdx = 0; anIdx < 2; ++anIdx)
2367 if (!aPrograms[anIdx].IsNull())
2369 aResult &= theGlContext->BindProgram (aPrograms[anIdx]);
2371 if (!myTextureEnv.IsNull())
2373 myTextureEnv->Bind (theGlContext,
2374 GL_TEXTURE0 + OpenGl_RT_EnvironmentMapTexture);
2376 aResult &= aPrograms[anIdx]->SetUniform (theGlContext,
2377 myUniformLocations[anIdx][OpenGl_RT_uSphereMapEnabled], 1);
2381 aResult &= aPrograms[anIdx]->SetUniform (theGlContext,
2382 myUniformLocations[anIdx][OpenGl_RT_uSphereMapEnabled], 0);
2387 myToUpdateEnvironmentMap = Standard_False;
2389 theGlContext->BindProgram (NULL);
2394 // =======================================================================
2395 // function : setUniformState
2396 // purpose : Sets uniform state for the given ray-tracing shader program
2397 // =======================================================================
2398 Standard_Boolean OpenGl_View::setUniformState (const Standard_Integer theProgramId,
2399 const Standard_Integer theWinSizeX,
2400 const Standard_Integer theWinSizeY,
2401 const Handle(OpenGl_Context)& theGlContext)
2403 // Get projection state
2404 OpenGl_MatrixState<Standard_ShortReal>& aCntxProjectionState = theGlContext->ProjectionState;
2406 OpenGl_Mat4 aViewPrjMat;
2407 OpenGl_Mat4 anUnviewMat;
2408 OpenGl_Vec3 aOrigins[4];
2409 OpenGl_Vec3 aDirects[4];
2411 updateCamera (myCamera->OrientationMatrixF(),
2412 aCntxProjectionState.Current(),
2418 Handle(OpenGl_ShaderProgram)& theProgram = theProgramId == 0
2420 : myPostFSAAProgram;
2422 if (theProgram.IsNull())
2424 return Standard_False;
2428 theProgram->SetUniform (theGlContext,
2429 myUniformLocations[theProgramId][OpenGl_RT_uOriginLB], aOrigins[0]);
2430 theProgram->SetUniform (theGlContext,
2431 myUniformLocations[theProgramId][OpenGl_RT_uOriginRB], aOrigins[1]);
2432 theProgram->SetUniform (theGlContext,
2433 myUniformLocations[theProgramId][OpenGl_RT_uOriginLT], aOrigins[2]);
2434 theProgram->SetUniform (theGlContext,
2435 myUniformLocations[theProgramId][OpenGl_RT_uOriginRT], aOrigins[3]);
2436 theProgram->SetUniform (theGlContext,
2437 myUniformLocations[theProgramId][OpenGl_RT_uDirectLB], aDirects[0]);
2438 theProgram->SetUniform (theGlContext,
2439 myUniformLocations[theProgramId][OpenGl_RT_uDirectRB], aDirects[1]);
2440 theProgram->SetUniform (theGlContext,
2441 myUniformLocations[theProgramId][OpenGl_RT_uDirectLT], aDirects[2]);
2442 theProgram->SetUniform (theGlContext,
2443 myUniformLocations[theProgramId][OpenGl_RT_uDirectRT], aDirects[3]);
2444 theProgram->SetUniform (theGlContext,
2445 myUniformLocations[theProgramId][OpenGl_RT_uViewPrMat], aViewPrjMat);
2446 theProgram->SetUniform (theGlContext,
2447 myUniformLocations[theProgramId][OpenGl_RT_uUnviewMat], anUnviewMat);
2449 // Set ray-tracing intersection parameters
2450 theProgram->SetUniform (theGlContext,
2451 myUniformLocations[theProgramId][OpenGl_RT_uSceneRad], myRaytraceSceneRadius);
2452 theProgram->SetUniform (theGlContext,
2453 myUniformLocations[theProgramId][OpenGl_RT_uSceneEps], myRaytraceSceneEpsilon);
2455 const Standard_Integer aLightSourceBufferSize =
2456 static_cast<Standard_Integer> (myRaytraceGeometry.Sources.size());
2458 // Set ray-tracing light source parameters
2459 theProgram->SetUniform (theGlContext,
2460 myUniformLocations[theProgramId][OpenGl_RT_uLightCount], aLightSourceBufferSize);
2461 theProgram->SetUniform (theGlContext,
2462 myUniformLocations[theProgramId][OpenGl_RT_uLightAmbnt], myRaytraceGeometry.Ambient);
2464 // Enable/disable run time rendering effects
2465 theProgram->SetUniform (theGlContext,
2466 myUniformLocations[theProgramId][OpenGl_RT_uShadowsEnabled], myRenderParams.IsShadowEnabled ? 1 : 0);
2467 theProgram->SetUniform (theGlContext,
2468 myUniformLocations[theProgramId][OpenGl_RT_uReflectEnabled], myRenderParams.IsReflectionEnabled ? 1 : 0);
2470 // Set screen dimensions
2471 myRaytraceProgram->SetUniform (theGlContext,
2472 myUniformLocations[theProgramId][OpenGl_RT_uWinSizeX], theWinSizeX);
2473 myRaytraceProgram->SetUniform (theGlContext,
2474 myUniformLocations[theProgramId][OpenGl_RT_uWinSizeY], theWinSizeY);
2476 if (myRenderParams.IsGlobalIlluminationEnabled) // if Monte-Carlo sampling enabled
2478 theProgram->SetUniform (theGlContext,
2479 myUniformLocations[theProgramId][OpenGl_RT_uBlockedRngEnabled], myRenderParams.CoherentPathTracingMode ? 1 : 0);
2482 // Set array of 64-bit texture handles
2483 if (theGlContext->arbTexBindless != NULL && myRaytraceGeometry.HasTextures())
2485 const std::vector<GLuint64>& aTextures = myRaytraceGeometry.TextureHandles();
2487 theProgram->SetUniform (theGlContext, myUniformLocations[theProgramId][OpenGl_RT_uTexSamplersArray],
2488 static_cast<GLsizei> (aTextures.size()), reinterpret_cast<const OpenGl_Vec2u*> (&aTextures.front()));
2491 // Set background colors (only gradient background supported)
2492 if (myBgGradientArray != NULL && myBgGradientArray->IsDefined())
2494 theProgram->SetUniform (theGlContext,
2495 myUniformLocations[theProgramId][OpenGl_RT_uBackColorTop], myBgGradientArray->GradientColor (0));
2496 theProgram->SetUniform (theGlContext,
2497 myUniformLocations[theProgramId][OpenGl_RT_uBackColorBot], myBgGradientArray->GradientColor (1));
2501 const OpenGl_Vec4& aBackColor = myBgColor;
2503 theProgram->SetUniform (theGlContext,
2504 myUniformLocations[theProgramId][OpenGl_RT_uBackColorTop], aBackColor);
2505 theProgram->SetUniform (theGlContext,
2506 myUniformLocations[theProgramId][OpenGl_RT_uBackColorBot], aBackColor);
2509 theProgram->SetUniform (theGlContext,
2510 myUniformLocations[theProgramId][OpenGl_RT_uSphereMapForBack], myRenderParams.UseEnvironmentMapBackground ? 1 : 0);
2512 return Standard_True;
2515 // =======================================================================
2516 // function : bindRaytraceTextures
2517 // purpose : Binds ray-trace textures to corresponding texture units
2518 // =======================================================================
2519 void OpenGl_View::bindRaytraceTextures (const Handle(OpenGl_Context)& theGlContext)
2521 if (myRaytraceParameters.AdaptiveScreenSampling)
2523 #if !defined(GL_ES_VERSION_2_0)
2524 theGlContext->core42->glBindImageTexture (OpenGl_RT_OutputImageLft,
2525 myRaytraceOutputTexture[0]->TextureId(), 0, GL_TRUE, 0, GL_READ_WRITE, GL_R32F);
2526 theGlContext->core42->glBindImageTexture (OpenGl_RT_OutputImageRgh,
2527 myRaytraceOutputTexture[1]->TextureId(), 0, GL_TRUE, 0, GL_READ_WRITE, GL_R32F);
2529 theGlContext->core42->glBindImageTexture (OpenGl_RT_VisualErrorImage,
2530 myRaytraceVisualErrorTexture->TextureId(), 0, GL_TRUE, 0, GL_READ_WRITE, GL_R32I);
2531 theGlContext->core42->glBindImageTexture (OpenGl_RT_TileOffsetsImage,
2532 myRaytraceTileOffsetsTexture->TextureId(), 0, GL_TRUE, 0, GL_READ_ONLY, GL_RG32I);
2536 mySceneMinPointTexture->BindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_SceneMinPointTexture);
2537 mySceneMaxPointTexture->BindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_SceneMaxPointTexture);
2538 mySceneNodeInfoTexture->BindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_SceneNodeInfoTexture);
2539 myGeometryVertexTexture->BindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryVertexTexture);
2540 myGeometryNormalTexture->BindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryNormalTexture);
2541 myGeometryTexCrdTexture->BindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryTexCrdTexture);
2542 myGeometryTriangTexture->BindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryTriangTexture);
2543 mySceneTransformTexture->BindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_SceneTransformTexture);
2544 myRaytraceMaterialTexture->BindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_RaytraceMaterialTexture);
2545 myRaytraceLightSrcTexture->BindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_RaytraceLightSrcTexture);
2548 // =======================================================================
2549 // function : unbindRaytraceTextures
2550 // purpose : Unbinds ray-trace textures from corresponding texture units
2551 // =======================================================================
2552 void OpenGl_View::unbindRaytraceTextures (const Handle(OpenGl_Context)& theGlContext)
2554 mySceneMinPointTexture->UnbindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_SceneMinPointTexture);
2555 mySceneMaxPointTexture->UnbindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_SceneMaxPointTexture);
2556 mySceneNodeInfoTexture->UnbindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_SceneNodeInfoTexture);
2557 myGeometryVertexTexture->UnbindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryVertexTexture);
2558 myGeometryNormalTexture->UnbindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryNormalTexture);
2559 myGeometryTexCrdTexture->UnbindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryTexCrdTexture);
2560 myGeometryTriangTexture->UnbindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryTriangTexture);
2561 mySceneTransformTexture->UnbindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_SceneTransformTexture);
2562 myRaytraceMaterialTexture->UnbindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_RaytraceMaterialTexture);
2563 myRaytraceLightSrcTexture->UnbindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_RaytraceLightSrcTexture);
2565 theGlContext->core15fwd->glActiveTexture (GL_TEXTURE0);
2568 // =======================================================================
2569 // function : runRaytraceShaders
2570 // purpose : Runs ray-tracing shader programs
2571 // =======================================================================
2572 Standard_Boolean OpenGl_View::runRaytraceShaders (const Standard_Integer theSizeX,
2573 const Standard_Integer theSizeY,
2574 Graphic3d_Camera::Projection theProjection,
2575 OpenGl_FrameBuffer* theReadDrawFbo,
2576 const Handle(OpenGl_Context)& theGlContext)
2578 Standard_Boolean aResult = theGlContext->BindProgram (myRaytraceProgram);
2580 aResult &= setUniformState (0,
2585 if (myRaytraceParameters.GlobalIllumination) // path tracing
2587 aResult &= runPathtrace (theProjection, theReadDrawFbo, theGlContext);
2589 else // Whitted-style ray-tracing
2591 aResult &= runRaytrace (theSizeX, theSizeY, theProjection, theReadDrawFbo, theGlContext);
2597 // =======================================================================
2598 // function : runRaytrace
2599 // purpose : Runs Whitted-style ray-tracing
2600 // =======================================================================
2601 Standard_Boolean OpenGl_View::runRaytrace (const Standard_Integer theSizeX,
2602 const Standard_Integer theSizeY,
2603 Graphic3d_Camera::Projection theProjection,
2604 OpenGl_FrameBuffer* theReadDrawFbo,
2605 const Handle(OpenGl_Context)& theGlContext)
2607 Standard_Boolean aResult = Standard_True;
2609 bindRaytraceTextures (theGlContext);
2611 Handle(OpenGl_FrameBuffer) aRenderImageFramebuffer;
2612 Handle(OpenGl_FrameBuffer) aDepthSourceFramebuffer;
2614 // Choose proper set of frame buffers for stereo rendering
2615 const Standard_Integer aFBOIdx (theProjection == Graphic3d_Camera::Projection_MonoRightEye);
2617 if (myRenderParams.IsAntialiasingEnabled) // if second FSAA pass is used
2619 myRaytraceFBO1[aFBOIdx]->BindBuffer (theGlContext);
2621 glClear (GL_DEPTH_BUFFER_BIT); // render the image with depth
2624 theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
2626 if (myRenderParams.IsAntialiasingEnabled)
2628 glDisable (GL_DEPTH_TEST); // improve jagged edges without depth buffer
2630 // bind ray-tracing output image as input
2631 myRaytraceFBO1[aFBOIdx]->ColorTexture()->Bind (theGlContext, GL_TEXTURE0 + OpenGl_RT_FsaaInputTexture);
2633 aResult &= theGlContext->BindProgram (myPostFSAAProgram);
2635 aResult &= setUniformState (1 /* FSAA ID */,
2640 // Perform multi-pass adaptive FSAA using ping-pong technique.
2641 // We use 'FLIPTRI' sampling pattern changing for every pixel
2642 // (3 additional samples per pixel, the 1st sample is already
2643 // available from initial ray-traced image).
2644 for (Standard_Integer anIt = 1; anIt < 4; ++anIt)
2646 GLfloat aOffsetX = 1.f / theSizeX;
2647 GLfloat aOffsetY = 1.f / theSizeY;
2665 aResult &= myPostFSAAProgram->SetUniform (theGlContext,
2666 myUniformLocations[1][OpenGl_RT_uSamples], anIt + 1);
2667 aResult &= myPostFSAAProgram->SetUniform (theGlContext,
2668 myUniformLocations[1][OpenGl_RT_uOffsetX], aOffsetX);
2669 aResult &= myPostFSAAProgram->SetUniform (theGlContext,
2670 myUniformLocations[1][OpenGl_RT_uOffsetY], aOffsetY);
2672 Handle(OpenGl_FrameBuffer)& aFramebuffer = anIt % 2
2673 ? myRaytraceFBO2[aFBOIdx]
2674 : myRaytraceFBO1[aFBOIdx];
2676 aFramebuffer->BindBuffer (theGlContext);
2678 // perform adaptive FSAA pass
2679 theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
2681 aFramebuffer->ColorTexture()->Bind (theGlContext, GL_TEXTURE0 + OpenGl_RT_FsaaInputTexture);
2684 aRenderImageFramebuffer = myRaytraceFBO2[aFBOIdx];
2685 aDepthSourceFramebuffer = myRaytraceFBO1[aFBOIdx];
2687 glEnable (GL_DEPTH_TEST);
2689 // Display filtered image
2690 theGlContext->BindProgram (myOutImageProgram);
2692 if (theReadDrawFbo != NULL)
2694 theReadDrawFbo->BindBuffer (theGlContext);
2698 aRenderImageFramebuffer->UnbindBuffer (theGlContext);
2701 aRenderImageFramebuffer->ColorTexture()->Bind (
2702 theGlContext, GL_TEXTURE0 + OpenGl_RT_PrevAccumTexture);
2704 aDepthSourceFramebuffer->DepthStencilTexture()->Bind (
2705 theGlContext, GL_TEXTURE0 + OpenGl_RT_RaytraceDepthTexture);
2707 // copy the output image with depth values
2708 theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
2710 aDepthSourceFramebuffer->DepthStencilTexture()->Unbind (
2711 theGlContext, GL_TEXTURE0 + OpenGl_RT_RaytraceDepthTexture);
2713 aRenderImageFramebuffer->ColorTexture()->Unbind (
2714 theGlContext, GL_TEXTURE0 + OpenGl_RT_PrevAccumTexture);
2717 unbindRaytraceTextures (theGlContext);
2719 theGlContext->BindProgram (NULL);
2724 // =======================================================================
2725 // function : runPathtrace
2726 // purpose : Runs path tracing shader
2727 // =======================================================================
2728 Standard_Boolean OpenGl_View::runPathtrace (const Graphic3d_Camera::Projection theProjection,
2729 OpenGl_FrameBuffer* theReadDrawFbo,
2730 const Handle(OpenGl_Context)& theGlContext)
2732 Standard_Boolean aResult = Standard_True;
2734 if (myRaytraceParameters.AdaptiveScreenSampling)
2736 if (myAccumFrames == 0)
2738 myTileSampler.Reset(); // reset tile sampler to its initial state
2741 // We upload tile offset texture each 4 frames in order
2742 // to minimize overhead of additional memory bandwidth.
2743 // Adaptive sampling is starting after first 10 frames.
2744 if (myAccumFrames % 4 == 0)
2746 myTileSampler.Upload (theGlContext, myRaytraceTileOffsetsTexture, myAccumFrames > 10);
2750 bindRaytraceTextures (theGlContext);
2752 Handle(OpenGl_FrameBuffer) aRenderImageFramebuffer;
2753 Handle(OpenGl_FrameBuffer) aDepthSourceFramebuffer;
2754 Handle(OpenGl_FrameBuffer) anAccumImageFramebuffer;
2756 // Choose proper set of frame buffers for stereo rendering
2757 const Standard_Integer aFBOIdx (theProjection == Graphic3d_Camera::Projection_MonoRightEye);
2759 const Standard_Integer anImageId = (aFBOIdx != 0)
2760 ? OpenGl_RT_OutputImageRgh
2761 : OpenGl_RT_OutputImageLft;
2763 aRenderImageFramebuffer = myAccumFrames % 2 ? myRaytraceFBO1[aFBOIdx] : myRaytraceFBO2[aFBOIdx];
2764 anAccumImageFramebuffer = myAccumFrames % 2 ? myRaytraceFBO2[aFBOIdx] : myRaytraceFBO1[aFBOIdx];
2766 aDepthSourceFramebuffer = aRenderImageFramebuffer;
2768 anAccumImageFramebuffer->ColorTexture()->Bind (
2769 theGlContext, GL_TEXTURE0 + OpenGl_RT_PrevAccumTexture);
2771 aRenderImageFramebuffer->BindBuffer (theGlContext);
2773 if (myAccumFrames == 0)
2775 myRNG.SetSeed(); // start RNG from beginning
2778 // Clear adaptive screen sampling images
2779 if (myRaytraceParameters.AdaptiveScreenSampling)
2781 #if !defined(GL_ES_VERSION_2_0)
2782 if (myAccumFrames == 0)
2784 theGlContext->core44->glClearTexImage (myRaytraceOutputTexture[aFBOIdx]->TextureId(), 0, GL_RED, GL_FLOAT, NULL);
2787 theGlContext->core44->glClearTexImage (myRaytraceVisualErrorTexture->TextureId(), 0, GL_RED_INTEGER, GL_INT, NULL);
2791 // Set frame accumulation weight
2792 myRaytraceProgram->SetUniform (theGlContext,
2793 myUniformLocations[0][OpenGl_RT_uSampleWeight], 1.f / (myAccumFrames + 1));
2795 // Set random number generator seed
2796 myRaytraceProgram->SetUniform (theGlContext,
2797 myUniformLocations[0][OpenGl_RT_uFrameRndSeed], static_cast<Standard_Integer> (myRNG.NextInt() >> 2));
2799 // Set image uniforms for render program
2800 myRaytraceProgram->SetUniform (theGlContext,
2801 myUniformLocations[0][OpenGl_RT_uRenderImage], anImageId);
2802 myRaytraceProgram->SetUniform (theGlContext,
2803 myUniformLocations[0][OpenGl_RT_uOffsetImage], OpenGl_RT_TileOffsetsImage);
2805 glDisable (GL_DEPTH_TEST);
2807 // Generate for the given RNG seed
2808 theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
2810 // Output accumulated path traced image
2811 theGlContext->BindProgram (myOutImageProgram);
2813 if (myRaytraceParameters.AdaptiveScreenSampling)
2815 // Set uniforms for display program
2816 myOutImageProgram->SetUniform (theGlContext, "uRenderImage", anImageId);
2817 myOutImageProgram->SetUniform (theGlContext, "uAccumFrames", myAccumFrames);
2818 myOutImageProgram->SetUniform (theGlContext, "uVarianceImage", OpenGl_RT_VisualErrorImage);
2819 myOutImageProgram->SetUniform (theGlContext, "uDebugAdaptive", myRenderParams.ShowSamplingTiles ? 1 : 0);
2822 if (theReadDrawFbo != NULL)
2824 theReadDrawFbo->BindBuffer (theGlContext);
2828 aRenderImageFramebuffer->UnbindBuffer (theGlContext);
2831 aRenderImageFramebuffer->ColorTexture()->Bind (
2832 theGlContext, GL_TEXTURE0 + OpenGl_RT_PrevAccumTexture);
2834 glEnable (GL_DEPTH_TEST);
2836 // Copy accumulated image with correct depth values
2837 theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
2839 aRenderImageFramebuffer->ColorTexture()->Unbind (
2840 theGlContext, GL_TEXTURE0 + OpenGl_RT_PrevAccumTexture);
2842 if (myRaytraceParameters.AdaptiveScreenSampling)
2844 myRaytraceVisualErrorTexture->Bind (theGlContext);
2846 // Download visual error map from the GPU and build
2847 // adjusted tile offsets for optimal image sampling
2848 myTileSampler.GrabVarianceMap (theGlContext);
2851 unbindRaytraceTextures (theGlContext);
2853 theGlContext->BindProgram (NULL);
2858 // =======================================================================
2859 // function : raytrace
2860 // purpose : Redraws the window using OpenGL/GLSL ray-tracing
2861 // =======================================================================
2862 Standard_Boolean OpenGl_View::raytrace (const Standard_Integer theSizeX,
2863 const Standard_Integer theSizeY,
2864 Graphic3d_Camera::Projection theProjection,
2865 OpenGl_FrameBuffer* theReadDrawFbo,
2866 const Handle(OpenGl_Context)& theGlContext)
2868 if (!initRaytraceResources (theGlContext))
2870 return Standard_False;
2873 if (!updateRaytraceBuffers (theSizeX, theSizeY, theGlContext))
2875 return Standard_False;
2878 if (!updateRaytraceEnvironmentMap (theGlContext))
2880 return Standard_False;
2883 OpenGl_Mat4 aLightSourceMatrix;
2885 // Get inversed model-view matrix for transforming lights
2886 myCamera->OrientationMatrixF().Inverted (aLightSourceMatrix);
2888 if (!updateRaytraceLightSources (aLightSourceMatrix, theGlContext))
2890 return Standard_False;
2893 // Generate image using Whitted-style ray-tracing or path tracing
2894 if (myIsRaytraceDataValid)
2896 myRaytraceScreenQuad.BindVertexAttrib (theGlContext, Graphic3d_TOA_POS);
2898 if (!myRaytraceGeometry.AcquireTextures (theGlContext))
2900 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR,
2901 0, GL_DEBUG_SEVERITY_MEDIUM, "Error: Failed to acquire OpenGL image textures");
2904 glDisable (GL_BLEND);
2906 const Standard_Boolean aResult = runRaytraceShaders (theSizeX,
2914 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR,
2915 0, GL_DEBUG_SEVERITY_MEDIUM, "Error: Failed to execute ray-tracing shaders");
2918 if (!myRaytraceGeometry.ReleaseTextures (theGlContext))
2920 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR,
2921 0, GL_DEBUG_SEVERITY_MEDIUM, "Error: Failed to release OpenGL image textures");
2924 myRaytraceScreenQuad.UnbindVertexAttrib (theGlContext, Graphic3d_TOA_POS);
2927 return Standard_True;