// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
-#include <Graphic3d_TextureParams.hxx>
+#include <OpenGl_View.hxx>
-#include <OpenGl_FrameBuffer.hxx>
+#include <Graphic3d_TextureParams.hxx>
#include <OpenGl_PrimitiveArray.hxx>
#include <OpenGl_VertexBuffer.hxx>
-#include <OpenGl_View.hxx>
-
+#include <OpenGl_GlCore44.hxx>
#include <OSD_Protection.hxx>
#include <OSD_File.hxx>
+#include "../Shaders/Shaders_RaytraceBase_vs.pxx"
+#include "../Shaders/Shaders_RaytraceBase_fs.pxx"
+#include "../Shaders/Shaders_PathtraceBase_fs.pxx"
+#include "../Shaders/Shaders_RaytraceRender_fs.pxx"
+#include "../Shaders/Shaders_RaytraceSmooth_fs.pxx"
+#include "../Shaders/Shaders_Display_fs.pxx"
+
using namespace OpenGl_Raytrace;
//! Use this macro to output ray-tracing debug info
#include <OSD_Timer.hxx>
#endif
+namespace
+{
+ static const OpenGl_Vec4 THE_WHITE_COLOR (1.0f, 1.0f, 1.0f, 1.0f);
+ static const OpenGl_Vec4 THE_BLACK_COLOR (0.0f, 0.0f, 0.0f, 1.0f);
+}
+
+namespace
+{
+ //! Defines OpenGL texture samplers.
+ static const Graphic3d_TextureUnit OpenGl_RT_EnvironmentMapTexture = Graphic3d_TextureUnit_0;
+
+ static const Graphic3d_TextureUnit OpenGl_RT_SceneNodeInfoTexture = Graphic3d_TextureUnit_1;
+ static const Graphic3d_TextureUnit OpenGl_RT_SceneMinPointTexture = Graphic3d_TextureUnit_2;
+ static const Graphic3d_TextureUnit OpenGl_RT_SceneMaxPointTexture = Graphic3d_TextureUnit_3;
+ static const Graphic3d_TextureUnit OpenGl_RT_SceneTransformTexture = Graphic3d_TextureUnit_4;
+
+ static const Graphic3d_TextureUnit OpenGl_RT_GeometryVertexTexture = Graphic3d_TextureUnit_5;
+ static const Graphic3d_TextureUnit OpenGl_RT_GeometryNormalTexture = Graphic3d_TextureUnit_6;
+ static const Graphic3d_TextureUnit OpenGl_RT_GeometryTexCrdTexture = Graphic3d_TextureUnit_7;
+ static const Graphic3d_TextureUnit OpenGl_RT_GeometryTriangTexture = Graphic3d_TextureUnit_8;
+
+ static const Graphic3d_TextureUnit OpenGl_RT_RaytraceMaterialTexture = Graphic3d_TextureUnit_9;
+ static const Graphic3d_TextureUnit OpenGl_RT_RaytraceLightSrcTexture = Graphic3d_TextureUnit_10;
+
+ static const Graphic3d_TextureUnit OpenGl_RT_FsaaInputTexture = Graphic3d_TextureUnit_11;
+ static const Graphic3d_TextureUnit OpenGl_RT_PrevAccumTexture = Graphic3d_TextureUnit_12;
+
+ static const Graphic3d_TextureUnit OpenGl_RT_RaytraceDepthTexture = Graphic3d_TextureUnit_13;
+}
+
// =======================================================================
-// function : UpdateRaytraceGeometry
+// function : updateRaytraceGeometry
// purpose : Updates 3D scene geometry for ray-tracing
// =======================================================================
Standard_Boolean OpenGl_View::updateRaytraceGeometry (const RaytraceUpdateMode theMode,
// modifications. This is light-weight procedure performed on each frame
if (theMode == OpenGl_GUM_CHECK)
{
- if (myLayersModificationStatus != myZLayers.ModificationState())
+ if (myRaytraceLayerListState != myZLayers.ModificationStateOfRaytracable())
{
return updateRaytraceGeometry (OpenGl_GUM_PREPARE, theViewId, theGlContext);
}
// applicable for ray-tracing
std::set<Standard_Size> anArrayIDs;
+ // Set to store all non-raytracable elements allowing tracking
+ // of changes in OpenGL scene (only for path tracing)
+ std::set<Standard_Integer> aNonRaytraceIDs;
+
const OpenGl_Layer& aLayer = myZLayers.Layer (Graphic3d_ZLayerId_Default);
if (aLayer.NbStructures() != 0)
{
- const OpenGl_ArrayOfStructure& aStructArray = aLayer.ArrayOfStructures();
+ const OpenGl_ArrayOfIndexedMapOfStructure& aStructArray = aLayer.ArrayOfStructures();
for (Standard_Integer anIndex = 0; anIndex < aStructArray.Length(); ++anIndex)
{
- for (OpenGl_SequenceOfStructure::Iterator aStructIt (aStructArray (anIndex)); aStructIt.More(); aStructIt.Next())
+ for (OpenGl_IndexedMapOfStructure::Iterator aStructIt (aStructArray (anIndex)); aStructIt.More(); aStructIt.Next())
{
const OpenGl_Structure* aStructure = aStructIt.Value();
{
return updateRaytraceGeometry (OpenGl_GUM_PREPARE, theViewId, theGlContext);
}
+ else if (aStructure->IsVisible() && myRaytraceParameters.GlobalIllumination)
+ {
+ aNonRaytraceIDs.insert (aStructure->highlight ? aStructure->Id : -aStructure->Id);
+ }
}
else if (theMode == OpenGl_GUM_PREPARE)
{
continue;
}
- for (OpenGl_Structure::GroupIterator aGroupIter (aStructure->DrawGroups()); aGroupIter.More(); aGroupIter.Next())
+ for (OpenGl_Structure::GroupIterator aGroupIter (aStructure->Groups()); aGroupIter.More(); aGroupIter.Next())
{
// Extract OpenGL elements from the group (primitives arrays)
for (const OpenGl_ElementNode* aNode = aGroupIter.Value()->FirstNode(); aNode != NULL; aNode = aNode->next)
else if (theMode == OpenGl_GUM_REBUILD)
{
// Actualize the hash map of structures - remove out-of-date records
- std::map<const OpenGl_Structure*, Standard_Size>::iterator anIter = myStructureStates.begin();
+ std::map<const OpenGl_Structure*, StructState>::iterator anIter = myStructureStates.begin();
while (anIter != myStructureStates.end())
{
}
// Actualize OpenGL layer list state
- myLayersModificationStatus = myZLayers.ModificationState();
+ myRaytraceLayerListState = myZLayers.ModificationStateOfRaytracable();
// Rebuild two-level acceleration structure
myRaytraceGeometry.ProcessAcceleration();
return uploadRaytraceData (theGlContext);
}
+ if (myRaytraceParameters.GlobalIllumination)
+ {
+ Standard_Boolean toRestart =
+ aNonRaytraceIDs.size() != myNonRaytraceStructureIDs.size();
+
+ for (std::set<Standard_Integer>::iterator anID = aNonRaytraceIDs.begin(); anID != aNonRaytraceIDs.end() && !toRestart; ++anID)
+ {
+ if (myNonRaytraceStructureIDs.find (*anID) == myNonRaytraceStructureIDs.end())
+ {
+ toRestart = Standard_True;
+ }
+ }
+
+ if (toRestart)
+ {
+ myAccumFrames = 0;
+ }
+
+ myNonRaytraceStructureIDs = aNonRaytraceIDs;
+ }
+
return Standard_True;
}
// =======================================================================
-// function : ToUpdateStructure
+// function : toUpdateStructure
// purpose : Checks to see if the structure is modified
// =======================================================================
Standard_Boolean OpenGl_View::toUpdateStructure (const OpenGl_Structure* theStructure)
return Standard_False; // did not contain ray-trace elements
}
- std::map<const OpenGl_Structure*, Standard_Size>::iterator aStructState = myStructureStates.find (theStructure);
+ std::map<const OpenGl_Structure*, StructState>::iterator aStructState = myStructureStates.find (theStructure);
- if (aStructState != myStructureStates.end())
+ if (aStructState == myStructureStates.end() || aStructState->second.StructureState != theStructure->ModificationState())
{
- return aStructState->second != theStructure->ModificationState();
+ return Standard_True;
+ }
+ else if (theStructure->InstancedStructure() != NULL)
+ {
+ return aStructState->second.InstancedState != theStructure->InstancedStructure()->ModificationState();
}
- return Standard_True;
+ return Standard_False;
}
// =======================================================================
-// function : BuildTextureTransform
+// function : buildTextureTransform
// purpose : Constructs texture transformation matrix
// =======================================================================
-void BuildTextureTransform (const Handle(Graphic3d_TextureParams)& theParams, BVH_Mat4f& theMatrix)
+void buildTextureTransform (const Handle(Graphic3d_TextureParams)& theParams, BVH_Mat4f& theMatrix)
{
theMatrix.InitIdentity();
+ if (theParams.IsNull())
+ {
+ return;
+ }
// Apply scaling
const Graphic3d_Vec2& aScale = theParams->Scale();
}
// =======================================================================
-// function : ConvertMaterial
+// function : convertMaterial
// purpose : Creates ray-tracing material properties
// =======================================================================
OpenGl_RaytraceMaterial OpenGl_View::convertMaterial (const OpenGl_AspectFace* theAspect,
{
OpenGl_RaytraceMaterial theMaterial;
- const OPENGL_SURF_PROP& aProperties = theAspect->IntFront();
+ const Graphic3d_MaterialAspect& aSrcMat = theAspect->Aspect()->FrontMaterial();
+ const OpenGl_Vec3& aMatCol = theAspect->Aspect()->InteriorColor();
+ const bool isPhysic = aSrcMat.MaterialType (Graphic3d_MATERIAL_PHYSIC);
+ const float aShine = 128.0f * float(aSrcMat.Shininess());
+
+ // ambient component
+ if (aSrcMat.ReflectionMode (Graphic3d_TOR_AMBIENT))
+ {
+ const OpenGl_Vec3& aSrcAmb = isPhysic ? aSrcMat.AmbientColor() : aMatCol;
+ theMaterial.Ambient = BVH_Vec4f (aSrcAmb * (float )aSrcMat.Ambient(), 1.0f);
+ }
+ else
+ {
+ theMaterial.Ambient = THE_BLACK_COLOR;
+ }
+
+ // diffusion component
+ if (aSrcMat.ReflectionMode (Graphic3d_TOR_DIFFUSE))
+ {
+ const OpenGl_Vec3& aSrcDif = isPhysic ? aSrcMat.DiffuseColor() : aMatCol;
+ theMaterial.Diffuse = BVH_Vec4f (aSrcDif * (float )aSrcMat.Diffuse(), -1.0f); // -1 is no texture
+ }
+ else
+ {
+ theMaterial.Diffuse = BVH_Vec4f (THE_BLACK_COLOR.rgb(), -1.0f);
+ }
+
+ // specular component
+ if (aSrcMat.ReflectionMode (Graphic3d_TOR_SPECULAR))
+ {
+ const OpenGl_Vec3& aSrcSpe = aSrcMat.SpecularColor();
+ const OpenGl_Vec3& aSrcSpe2 = isPhysic ? aSrcSpe : THE_WHITE_COLOR.rgb();
+ theMaterial.Specular = BVH_Vec4f (aSrcSpe2 * (float )aSrcMat.Specular(), aShine);
+
+ const Standard_ShortReal aMaxRefl = Max (theMaterial.Diffuse.x() + theMaterial.Specular.x(),
+ Max (theMaterial.Diffuse.y() + theMaterial.Specular.y(),
+ theMaterial.Diffuse.z() + theMaterial.Specular.z()));
- theMaterial.Ambient = BVH_Vec4f (
- (aProperties.isphysic ? aProperties.ambcol.rgb[0] : aProperties.matcol.rgb[0]) * aProperties.amb,
- (aProperties.isphysic ? aProperties.ambcol.rgb[1] : aProperties.matcol.rgb[1]) * aProperties.amb,
- (aProperties.isphysic ? aProperties.ambcol.rgb[2] : aProperties.matcol.rgb[2]) * aProperties.amb,
- 1.f);
+ const Standard_ShortReal aReflectionScale = 0.75f / aMaxRefl;
- theMaterial.Diffuse = BVH_Vec4f (
- (aProperties.isphysic ? aProperties.difcol.rgb[0] : aProperties.matcol.rgb[0]) * aProperties.diff,
- (aProperties.isphysic ? aProperties.difcol.rgb[1] : aProperties.matcol.rgb[1]) * aProperties.diff,
- (aProperties.isphysic ? aProperties.difcol.rgb[2] : aProperties.matcol.rgb[2]) * aProperties.diff,
- -1.f /* no texture */);
+ // ignore isPhysic here
+ theMaterial.Reflection = BVH_Vec4f (aSrcSpe * (float )aSrcMat.Specular() * aReflectionScale, 0.0f);
+ }
+ else
+ {
+ theMaterial.Specular = BVH_Vec4f (THE_BLACK_COLOR.rgb(), aShine);
+ }
- theMaterial.Specular = BVH_Vec4f (
- (aProperties.isphysic ? aProperties.speccol.rgb[0] : 1.f) * aProperties.spec,
- (aProperties.isphysic ? aProperties.speccol.rgb[1] : 1.f) * aProperties.spec,
- (aProperties.isphysic ? aProperties.speccol.rgb[2] : 1.f) * aProperties.spec,
- aProperties.shine);
+ // emission component
+ if (aSrcMat.ReflectionMode (Graphic3d_TOR_EMISSION))
+ {
+ const OpenGl_Vec3& aSrcEms = isPhysic ? aSrcMat.EmissiveColor() : aMatCol;
+ theMaterial.Emission = BVH_Vec4f (aSrcEms * (float )aSrcMat.Emissive(), 1.0f);
+ }
+ else
+ {
+ theMaterial.Emission = THE_BLACK_COLOR;
+ }
- theMaterial.Emission = BVH_Vec4f (
- (aProperties.isphysic ? aProperties.emscol.rgb[0] : aProperties.matcol.rgb[0]) * aProperties.emsv,
- (aProperties.isphysic ? aProperties.emscol.rgb[1] : aProperties.matcol.rgb[1]) * aProperties.emsv,
- (aProperties.isphysic ? aProperties.emscol.rgb[2] : aProperties.matcol.rgb[2]) * aProperties.emsv,
- 1.f);
+ const float anIndex = (float )aSrcMat.RefractionIndex();
+ theMaterial.Transparency = BVH_Vec4f (aSrcMat.Alpha(), aSrcMat.Transparency(),
+ anIndex == 0 ? 1.0f : anIndex,
+ anIndex == 0 ? 1.0f : 1.0f / anIndex);
- theMaterial.Transparency = BVH_Vec4f (aProperties.trans,
- 1.f - aProperties.trans,
- aProperties.index == 0 ? 1.f : aProperties.index,
- aProperties.index == 0 ? 1.f : 1.f / aProperties.index);
+ // Serialize physically-based material properties
+ const Graphic3d_BSDF& aBSDF = aSrcMat.BSDF();
- const Standard_ShortReal aMaxRefl = Max (theMaterial.Diffuse.x() + theMaterial.Specular.x(),
- Max (theMaterial.Diffuse.y() + theMaterial.Specular.y(),
- theMaterial.Diffuse.z() + theMaterial.Specular.z()));
+ theMaterial.BSDF.Kc = aBSDF.Kc;
+ theMaterial.BSDF.Ks = aBSDF.Ks;
+ theMaterial.BSDF.Kd = BVH_Vec4f (aBSDF.Kd, -1.f); // no texture
+ theMaterial.BSDF.Kt = BVH_Vec4f (aBSDF.Kt, 0.f);
+ theMaterial.BSDF.Le = BVH_Vec4f (aBSDF.Le, 0.f);
- const Standard_ShortReal aReflectionScale = 0.75f / aMaxRefl;
+ theMaterial.BSDF.Absorption = aBSDF.Absorption;
- theMaterial.Reflection = BVH_Vec4f (
- aProperties.speccol.rgb[0] * aProperties.spec * aReflectionScale,
- aProperties.speccol.rgb[1] * aProperties.spec * aReflectionScale,
- aProperties.speccol.rgb[2] * aProperties.spec * aReflectionScale,
- 0.f);
+ theMaterial.BSDF.FresnelCoat = aBSDF.FresnelCoat.Serialize ();
+ theMaterial.BSDF.FresnelBase = aBSDF.FresnelBase.Serialize ();
- if (theAspect->DoTextureMap())
+ // Handle material textures
+ if (!theAspect->Aspect()->ToMapTexture())
{
- if (theGlContext->arbTexBindless != NULL)
- {
- BuildTextureTransform (theAspect->TextureParams(), theMaterial.TextureTransform);
+ return theMaterial;
+ }
- // write texture ID in the w-component
- theMaterial.Diffuse.w() = static_cast<Standard_ShortReal> (
- myRaytraceGeometry.AddTexture (theAspect->TextureRes (theGlContext)));
- }
- else if (!myIsRaytraceWarnTextures)
- {
- const TCollection_ExtendedString aWarnMessage =
- "Warning: texturing in Ray-Trace requires GL_ARB_bindless_texture extension which is missing. "
- "Please try to update graphics card driver. At the moment textures will be ignored.";
+ const Handle(OpenGl_TextureSet)& aTextureSet = theAspect->TextureSet (theGlContext);
+ if (aTextureSet.IsNull()
+ || aTextureSet->IsEmpty()
+ || aTextureSet->First().IsNull())
+ {
+ return theMaterial;
+ }
- theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
- GL_DEBUG_TYPE_PORTABILITY_ARB, 0, GL_DEBUG_SEVERITY_HIGH_ARB, aWarnMessage);
+ if (theGlContext->HasRayTracingTextures())
+ {
+ const Handle(OpenGl_Texture)& aTexture = aTextureSet->First();
+ buildTextureTransform (aTexture->Sampler()->Parameters(), theMaterial.TextureTransform);
- myIsRaytraceWarnTextures = Standard_True;
- }
+ // write texture ID to diffuse w-component
+ theMaterial.Diffuse.w() = theMaterial.BSDF.Kd.w() = static_cast<Standard_ShortReal> (myRaytraceGeometry.AddTexture (aTexture));
+ }
+ else if (!myIsRaytraceWarnTextures)
+ {
+ const TCollection_ExtendedString aWarnMessage =
+ "Warning: texturing in Ray-Trace requires GL_ARB_bindless_texture extension which is missing. "
+ "Please try to update graphics card driver. At the moment textures will be ignored.";
+
+ theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
+ GL_DEBUG_TYPE_PORTABILITY, 0, GL_DEBUG_SEVERITY_HIGH, aWarnMessage);
+
+ myIsRaytraceWarnTextures = Standard_True;
}
return theMaterial;
}
// =======================================================================
-// function : AddRaytraceStructure
+// function : addRaytraceStructure
// purpose : Adds OpenGL structure to ray-traced scene geometry
// =======================================================================
Standard_Boolean OpenGl_View::addRaytraceStructure (const OpenGl_Structure* theStructure,
{
if (!theStructure->IsVisible())
{
- myStructureStates[theStructure] = theStructure->ModificationState();
+ myStructureStates[theStructure] = StructState (theStructure);
return Standard_True;
}
// Get structure material
- Standard_Integer aStructMatID = -1;
-
- if (theStructure->AspectFace() != NULL)
- {
- aStructMatID = static_cast<Standard_Integer> (myRaytraceGeometry.Materials.size());
-
- OpenGl_RaytraceMaterial aStructMaterial = convertMaterial (theStructure->AspectFace(), theGlContext);
-
- myRaytraceGeometry.Materials.push_back (aStructMaterial);
- }
-
- Standard_ShortReal aStructTransform[16];
-
- if (theStructure->Transformation()->mat != NULL)
- {
- for (Standard_Integer i = 0; i < 4; ++i)
- {
- for (Standard_Integer j = 0; j < 4; ++j)
- {
- aStructTransform[j * 4 + i] = theStructure->Transformation()->mat[i][j];
- }
- }
- }
-
- Standard_Boolean aResult = addRaytraceGroups (theStructure, aStructMatID,
- theStructure->Transformation()->mat ? aStructTransform : NULL, theGlContext);
+ OpenGl_RaytraceMaterial aDefaultMaterial;
+ Standard_Boolean aResult = addRaytraceGroups (theStructure, aDefaultMaterial, theStructure->Transformation(), theGlContext);
// Process all connected OpenGL structures
- for (OpenGl_ListOfStructure::Iterator anIts (theStructure->ConnectedStructures()); anIts.More(); anIts.Next())
+ const OpenGl_Structure* anInstanced = theStructure->InstancedStructure();
+
+ if (anInstanced != NULL && anInstanced->IsRaytracable())
{
- if (anIts.Value()->IsRaytracable())
- {
- aResult &= addRaytraceGroups (anIts.Value(), aStructMatID,
- theStructure->Transformation()->mat ? aStructTransform : NULL, theGlContext);
- }
+ aResult &= addRaytraceGroups (anInstanced, aDefaultMaterial, theStructure->Transformation(), theGlContext);
}
- myStructureStates[theStructure] = theStructure->ModificationState();
+ myStructureStates[theStructure] = StructState (theStructure);
return aResult;
}
// =======================================================================
-// function : AddRaytraceGroups
+// function : addRaytraceGroups
// purpose : Adds OpenGL groups to ray-traced scene geometry
// =======================================================================
-Standard_Boolean OpenGl_View::addRaytraceGroups (const OpenGl_Structure* theStructure,
- const Standard_Integer theStructMat,
- const Standard_ShortReal* theTransform,
- const Handle(OpenGl_Context)& theGlContext)
+Standard_Boolean OpenGl_View::addRaytraceGroups (const OpenGl_Structure* theStructure,
+ const OpenGl_RaytraceMaterial& theStructMat,
+ const Handle(Geom_Transformation)& theTrsf,
+ const Handle(OpenGl_Context)& theGlContext)
{
- for (OpenGl_Structure::GroupIterator aGroupIter (theStructure->DrawGroups()); aGroupIter.More(); aGroupIter.Next())
+ OpenGl_Mat4 aMat4;
+ for (OpenGl_Structure::GroupIterator aGroupIter (theStructure->Groups()); aGroupIter.More(); aGroupIter.Next())
{
// Get group material
- Standard_Integer aGroupMatID = -1;
+ OpenGl_RaytraceMaterial aGroupMaterial;
if (aGroupIter.Value()->AspectFace() != NULL)
{
- aGroupMatID = static_cast<Standard_Integer> (myRaytraceGeometry.Materials.size());
-
- OpenGl_RaytraceMaterial aGroupMaterial = convertMaterial (
+ aGroupMaterial = convertMaterial (
aGroupIter.Value()->AspectFace(), theGlContext);
-
- myRaytraceGeometry.Materials.push_back (aGroupMaterial);
}
- Standard_Integer aMatID = aGroupMatID < 0 ? theStructMat : aGroupMatID;
- if (aMatID < 0)
- {
- aMatID = static_cast<Standard_Integer> (myRaytraceGeometry.Materials.size());
+ Standard_Integer aMatID = static_cast<Standard_Integer> (myRaytraceGeometry.Materials.size());
- myRaytraceGeometry.Materials.push_back (OpenGl_RaytraceMaterial());
- }
+ // Use group material if available, otherwise use structure material
+ myRaytraceGeometry.Materials.push_back (
+ aGroupIter.Value()->AspectFace() != NULL ? aGroupMaterial : theStructMat);
// Add OpenGL elements from group (extract primitives arrays and aspects)
for (const OpenGl_ElementNode* aNode = aGroupIter.Value()->FirstNode(); aNode != NULL; aNode = aNode->next)
if (aSetIter != myArrayToTrianglesMap.end())
{
OpenGl_TriangleSet* aSet = aSetIter->second;
-
- BVH_Transform<Standard_ShortReal, 4>* aTransform = new BVH_Transform<Standard_ShortReal, 4>();
-
- if (theTransform != NULL)
+ opencascade::handle<BVH_Transform<Standard_ShortReal, 4> > aTransform = new BVH_Transform<Standard_ShortReal, 4>();
+ if (!theTrsf.IsNull())
{
- aTransform->SetTransform (*(reinterpret_cast<const BVH_Mat4f*> (theTransform)));
+ theTrsf->Trsf().GetMat4 (aMat4);
+ aTransform->SetTransform (aMat4);
}
aSet->SetProperties (aTransform);
-
if (aSet->MaterialIndex() != OpenGl_TriangleSet::INVALID_MATERIAL && aSet->MaterialIndex() != aMatID)
{
aSet->SetMaterialIndex (aMatID);
}
else
{
- NCollection_Handle<BVH_Object<Standard_ShortReal, 3> > aSet =
- addRaytracePrimitiveArray (aPrimArray, aMatID, 0);
-
- if (!aSet.IsNull())
+ if (Handle(OpenGl_TriangleSet) aSet = addRaytracePrimitiveArray (aPrimArray, aMatID, 0))
{
- BVH_Transform<Standard_ShortReal, 4>* aTransform = new BVH_Transform<Standard_ShortReal, 4>;
-
- if (theTransform != NULL)
+ opencascade::handle<BVH_Transform<Standard_ShortReal, 4> > aTransform = new BVH_Transform<Standard_ShortReal, 4>();
+ if (!theTrsf.IsNull())
{
- aTransform->SetTransform (*(reinterpret_cast<const BVH_Mat4f*> (theTransform)));
+ theTrsf->Trsf().GetMat4 (aMat4);
+ aTransform->SetTransform (aMat4);
}
aSet->SetProperties (aTransform);
-
myRaytraceGeometry.Objects().Append (aSet);
}
}
}
// =======================================================================
-// function : AddRaytracePrimitiveArray
+// function : addRaytracePrimitiveArray
// purpose : Adds OpenGL primitive array to ray-traced scene geometry
// =======================================================================
-OpenGl_TriangleSet* OpenGl_View::addRaytracePrimitiveArray (const OpenGl_PrimitiveArray* theArray,
- const Standard_Integer theMaterial,
- const OpenGl_Mat4* theTransform)
+Handle(OpenGl_TriangleSet) OpenGl_View::addRaytracePrimitiveArray (const OpenGl_PrimitiveArray* theArray,
+ const Standard_Integer theMaterial,
+ const OpenGl_Mat4* theTransform)
{
const Handle(Graphic3d_BoundBuffer)& aBounds = theArray->Bounds();
const Handle(Graphic3d_IndexBuffer)& anIndices = theArray->Indices();
#endif
|| anAttribs.IsNull())
{
- return NULL;
+ return Handle(OpenGl_TriangleSet)();
}
OpenGl_Mat4 aNormalMatrix;
-
if (theTransform != NULL)
{
Standard_ASSERT_RETURN (theTransform->Inverted (aNormalMatrix),
aNormalMatrix.Transpose();
}
- OpenGl_TriangleSet* aSet = new OpenGl_TriangleSet (theArray->GetUID());
+ Handle(OpenGl_TriangleSet) aSet = new OpenGl_TriangleSet (theArray->GetUID(), myRaytraceBVHBuilder);
{
aSet->Vertices.reserve (anAttribs->NbElements);
aSet->Normals.reserve (anAttribs->NbElements);
const size_t aVertFrom = aSet->Vertices.size();
- for (Standard_Integer anAttribIter = 0; anAttribIter < anAttribs->NbAttributes; ++anAttribIter)
+ Standard_Integer anAttribIndex = 0;
+ Standard_Size anAttribStride = 0;
+ if (const Standard_Byte* aPosData = anAttribs->AttributeData (Graphic3d_TOA_POS, anAttribIndex, anAttribStride))
{
- const Graphic3d_Attribute& anAttrib = anAttribs->Attribute (anAttribIter);
- const size_t anOffset = anAttribs->AttributeOffset (anAttribIter);
- if (anAttrib.Id == Graphic3d_TOA_POS)
+ const Graphic3d_Attribute& anAttrib = anAttribs->Attribute (anAttribIndex);
+ if (anAttrib.DataType == Graphic3d_TOD_VEC2
+ || anAttrib.DataType == Graphic3d_TOD_VEC3
+ || anAttrib.DataType == Graphic3d_TOD_VEC4)
{
- if (anAttrib.DataType == Graphic3d_TOD_VEC3
- || anAttrib.DataType == Graphic3d_TOD_VEC4)
- {
- for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
- {
- aSet->Vertices.push_back (
- *reinterpret_cast<const Graphic3d_Vec3*> (anAttribs->value (aVertIter) + anOffset));
- }
- }
- else if (anAttrib.DataType == Graphic3d_TOD_VEC2)
+ for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
{
- for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
- {
- const Standard_ShortReal* aCoords =
- reinterpret_cast<const Standard_ShortReal*> (anAttribs->value (aVertIter) + anOffset);
-
- aSet->Vertices.push_back (BVH_Vec3f (aCoords[0], aCoords[1], 0.0f));
- }
+ const float* aCoords = reinterpret_cast<const float*> (aPosData + anAttribStride * aVertIter);
+ aSet->Vertices.push_back (BVH_Vec3f (aCoords[0], aCoords[1], anAttrib.DataType != Graphic3d_TOD_VEC2 ? aCoords[2] : 0.0f));
}
}
- else if (anAttrib.Id == Graphic3d_TOA_NORM)
+ }
+ if (const Standard_Byte* aNormData = anAttribs->AttributeData (Graphic3d_TOA_NORM, anAttribIndex, anAttribStride))
+ {
+ const Graphic3d_Attribute& anAttrib = anAttribs->Attribute (anAttribIndex);
+ if (anAttrib.DataType == Graphic3d_TOD_VEC3
+ || anAttrib.DataType == Graphic3d_TOD_VEC4)
{
- if (anAttrib.DataType == Graphic3d_TOD_VEC3
- || anAttrib.DataType == Graphic3d_TOD_VEC4)
+ for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
{
- for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
- {
- aSet->Normals.push_back (
- *reinterpret_cast<const Graphic3d_Vec3*> (anAttribs->value (aVertIter) + anOffset));
- }
+ aSet->Normals.push_back (*reinterpret_cast<const Graphic3d_Vec3*> (aNormData + anAttribStride * aVertIter));
}
}
- else if (anAttrib.Id == Graphic3d_TOA_UV)
+ }
+ if (const Standard_Byte* aTexData = anAttribs->AttributeData (Graphic3d_TOA_UV, anAttribIndex, anAttribStride))
+ {
+ const Graphic3d_Attribute& anAttrib = anAttribs->Attribute (anAttribIndex);
+ if (anAttrib.DataType == Graphic3d_TOD_VEC2)
{
- if (anAttrib.DataType == Graphic3d_TOD_VEC2)
+ for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
{
- for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
- {
- aSet->TexCrds.push_back (
- *reinterpret_cast<const Graphic3d_Vec2*> (anAttribs->value (aVertIter) + anOffset));
- }
+ aSet->TexCrds.push_back (*reinterpret_cast<const Graphic3d_Vec2*> (aTexData + anAttribStride * aVertIter));
}
}
}
if (!addRaytraceVertexIndices (*aSet, theMaterial, aVertNum, aBoundStart, *theArray))
{
- delete aSet;
- return NULL;
+ aSet.Nullify();
+ return Handle(OpenGl_TriangleSet)();
}
aBoundStart += aVertNum;
if (!addRaytraceVertexIndices (*aSet, theMaterial, aVertNum, 0, *theArray))
{
- delete aSet;
- return NULL;
+ aSet.Nullify();
+ return Handle(OpenGl_TriangleSet)();
}
}
}
}
// =======================================================================
-// function : AddRaytraceVertexIndices
+// function : addRaytraceVertexIndices
// purpose : Adds vertex indices to ray-traced scene geometry
// =======================================================================
Standard_Boolean OpenGl_View::addRaytraceVertexIndices (OpenGl_TriangleSet& theSet,
}
// =======================================================================
-// function : AddRaytraceTriangleArray
+// function : addRaytraceTriangleArray
// purpose : Adds OpenGL triangle array to ray-traced scene geometry
// =======================================================================
Standard_Boolean OpenGl_View::addRaytraceTriangleArray (OpenGl_TriangleSet& theSet,
}
// =======================================================================
-// function : AddRaytraceTriangleFanArray
+// function : addRaytraceTriangleFanArray
// purpose : Adds OpenGL triangle fan array to ray-traced scene geometry
// =======================================================================
Standard_Boolean OpenGl_View::addRaytraceTriangleFanArray (OpenGl_TriangleSet& theSet,
}
// =======================================================================
-// function : AddRaytraceTriangleStripArray
+// function : addRaytraceTriangleStripArray
// purpose : Adds OpenGL triangle strip array to ray-traced scene geometry
// =======================================================================
Standard_Boolean OpenGl_View::addRaytraceTriangleStripArray (OpenGl_TriangleSet& theSet,
{
for (Standard_Integer aVert = theOffset, aCW = 0; aVert < theOffset + theCount - 2; ++aVert, aCW = (aCW + 1) % 2)
{
- theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + aCW ? 1 : 0),
- theIndices->Index (aVert + aCW ? 0 : 1),
+ theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + (aCW ? 1 : 0)),
+ theIndices->Index (aVert + (aCW ? 0 : 1)),
theIndices->Index (aVert + 2),
theMatID));
}
{
for (Standard_Integer aVert = theOffset, aCW = 0; aVert < theOffset + theCount - 2; ++aVert, aCW = (aCW + 1) % 2)
{
- theSet.Elements.push_back (BVH_Vec4i (aVert + aCW ? 1 : 0,
- aVert + aCW ? 0 : 1,
+ theSet.Elements.push_back (BVH_Vec4i (aVert + (aCW ? 1 : 0),
+ aVert + (aCW ? 0 : 1),
aVert + 2,
theMatID));
}
}
// =======================================================================
-// function : AddRaytraceQuadrangleArray
+// function : addRaytraceQuadrangleArray
// purpose : Adds OpenGL quad array to ray-traced scene geometry
// =======================================================================
Standard_Boolean OpenGl_View::addRaytraceQuadrangleArray (OpenGl_TriangleSet& theSet,
}
// =======================================================================
-// function : AddRaytraceQuadrangleStripArray
+// function : addRaytraceQuadrangleStripArray
// purpose : Adds OpenGL quad strip array to ray-traced scene geometry
// =======================================================================
Standard_Boolean OpenGl_View::addRaytraceQuadrangleStripArray (OpenGl_TriangleSet& theSet,
}
// =======================================================================
-// function : AddRaytracePolygonArray
+// function : addRaytracePolygonArray
// purpose : Adds OpenGL polygon array to ray-traced scene geometry
// =======================================================================
Standard_Boolean OpenGl_View::addRaytracePolygonArray (OpenGl_TriangleSet& theSet,
return Standard_True;
}
+const TCollection_AsciiString OpenGl_View::ShaderSource::EMPTY_PREFIX;
+
// =======================================================================
// function : Source
// purpose : Returns shader source combined with prefix
// =======================================================================
TCollection_AsciiString OpenGl_View::ShaderSource::Source() const
{
- static const TCollection_AsciiString aVersion = "#version 140";
+ const TCollection_AsciiString aVersion = "#version 140";
if (myPrefix.IsEmpty())
{
}
// =======================================================================
-// function : Load
+// function : LoadFromFiles
// purpose : Loads shader source from specified files
// =======================================================================
-void OpenGl_View::ShaderSource::Load (const TCollection_AsciiString* theFileNames,
- const Standard_Integer theCount)
+Standard_Boolean OpenGl_View::ShaderSource::LoadFromFiles (const TCollection_AsciiString* theFileNames,
+ const TCollection_AsciiString& thePrefix)
{
+ myError.Clear();
mySource.Clear();
+ myPrefix = thePrefix;
- for (Standard_Integer anIndex = 0; anIndex < theCount; ++anIndex)
+ TCollection_AsciiString aMissingFiles;
+ for (Standard_Integer anIndex = 0; !theFileNames[anIndex].IsEmpty(); ++anIndex)
{
OSD_File aFile (theFileNames[anIndex]);
-
- Standard_ASSERT_RETURN (aFile.Exists(),
- "Error: Failed to find shader source file", /* none */);
-
- aFile.Open (OSD_ReadOnly, OSD_Protection());
+ if (aFile.Exists())
+ {
+ aFile.Open (OSD_ReadOnly, OSD_Protection());
+ }
+ if (!aFile.IsOpen())
+ {
+ if (!aMissingFiles.IsEmpty())
+ {
+ aMissingFiles += ", ";
+ }
+ aMissingFiles += TCollection_AsciiString("'") + theFileNames[anIndex] + "'";
+ continue;
+ }
+ else if (!aMissingFiles.IsEmpty())
+ {
+ aFile.Close();
+ continue;
+ }
TCollection_AsciiString aSource;
+ aFile.Read (aSource, (Standard_Integer) aFile.Size());
+ if (!aSource.IsEmpty())
+ {
+ mySource += TCollection_AsciiString ("\n") + aSource;
+ }
+ aFile.Close();
+ }
- Standard_ASSERT_RETURN (aFile.IsOpen(),
- "Error: Failed to open shader source file", /* none */);
+ if (!aMissingFiles.IsEmpty())
+ {
+ myError = TCollection_AsciiString("Shader files ") + aMissingFiles + " are missing or inaccessible";
+ return Standard_False;
+ }
+ return Standard_True;
+}
- aFile.Read (aSource, (Standard_Integer) aFile.Size());
+// =======================================================================
+// function : LoadFromStrings
+// purpose :
+// =======================================================================
+Standard_Boolean OpenGl_View::ShaderSource::LoadFromStrings (const TCollection_AsciiString* theStrings,
+ const TCollection_AsciiString& thePrefix)
+{
+ myError.Clear();
+ mySource.Clear();
+ myPrefix = thePrefix;
+ for (Standard_Integer anIndex = 0; !theStrings[anIndex].IsEmpty(); ++anIndex)
+ {
+ TCollection_AsciiString aSource = theStrings[anIndex];
if (!aSource.IsEmpty())
{
mySource += TCollection_AsciiString ("\n") + aSource;
}
-
- aFile.Close();
}
+ return Standard_True;
}
// =======================================================================
-// function : GenerateShaderPrefix
+// function : generateShaderPrefix
// purpose : Generates shader prefix based on current ray-tracing options
// =======================================================================
TCollection_AsciiString OpenGl_View::generateShaderPrefix (const Handle(OpenGl_Context)& theGlContext) const
aPrefixString += TCollection_AsciiString ("\n#define TRANSPARENT_SHADOWS");
}
- // If OpenGL driver supports bindless textures,
- // activate texturing in ray-tracing mode
- if (theGlContext->arbTexBindless != NULL)
+ // If OpenGL driver supports bindless textures and texturing
+ // is actually used, activate texturing in ray-tracing mode
+ if (myRaytraceParameters.UseBindlessTextures && theGlContext->arbTexBindless != NULL)
{
aPrefixString += TCollection_AsciiString ("\n#define USE_TEXTURES") +
TCollection_AsciiString ("\n#define MAX_TEX_NUMBER ") + TCollection_AsciiString (OpenGl_RaytraceGeometry::MAX_TEX_NUMBER);
}
+ if (myRaytraceParameters.GlobalIllumination) // path tracing activated
+ {
+ aPrefixString += TCollection_AsciiString ("\n#define PATH_TRACING");
+
+ if (myRaytraceParameters.AdaptiveScreenSampling) // adaptive screen sampling requested
+ {
+ // to activate the feature we need OpenGL 4.4 and GL_NV_shader_atomic_float extension
+ if (theGlContext->IsGlGreaterEqual (4, 4) && theGlContext->CheckExtension ("GL_NV_shader_atomic_float"))
+ {
+ aPrefixString += TCollection_AsciiString ("\n#define ADAPTIVE_SAMPLING");
+ }
+ }
+
+ if (myRaytraceParameters.TwoSidedBsdfModels) // two-sided BSDFs requested
+ {
+ aPrefixString += TCollection_AsciiString ("\n#define TWO_SIDED_BXDF");
+ }
+
+ switch (myRaytraceParameters.ToneMappingMethod)
+ {
+ case Graphic3d_ToneMappingMethod_Disabled:
+ break;
+ case Graphic3d_ToneMappingMethod_Filmic:
+ aPrefixString += TCollection_AsciiString ("\n#define TONE_MAPPING_FILMIC");
+ break;
+ }
+ }
+
+ if (myRaytraceParameters.DepthOfField)
+ {
+ aPrefixString += TCollection_AsciiString("\n#define DEPTH_OF_FIELD");
+ }
+
return aPrefixString;
}
// =======================================================================
-// function : SafeFailBack
+// function : safeFailBack
// purpose : Performs safe exit when shaders initialization fails
// =======================================================================
Standard_Boolean OpenGl_View::safeFailBack (const TCollection_ExtendedString& theMessage,
const Handle(OpenGl_Context)& theGlContext)
{
- theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
- GL_DEBUG_TYPE_ERROR_ARB, 0, GL_DEBUG_SEVERITY_HIGH_ARB, theMessage);
+ theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
+ GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, theMessage);
myRaytraceInitStatus = OpenGl_RT_FAIL;
}
// =======================================================================
-// function : InitShader
+// function : initShader
// purpose : Creates new shader object with specified source
// =======================================================================
Handle(OpenGl_ShaderObject) OpenGl_View::initShader (const GLenum theType,
const TCollection_ExtendedString aMessage = TCollection_ExtendedString ("Error: Failed to create ") +
(theType == GL_VERTEX_SHADER ? "vertex" : "fragment") + " shader object";
- theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
- GL_DEBUG_TYPE_ERROR_ARB, 0, GL_DEBUG_SEVERITY_HIGH_ARB, aMessage);
+ theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
+ GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, aMessage);
aShader->Release (theGlContext.operator->());
const TCollection_ExtendedString aMessage = TCollection_ExtendedString ("Error: Failed to set ") +
(theType == GL_VERTEX_SHADER ? "vertex" : "fragment") + " shader source";
- theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
- GL_DEBUG_TYPE_ERROR_ARB, 0, GL_DEBUG_SEVERITY_HIGH_ARB, aMessage);
+ theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
+ GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, aMessage);
aShader->Release (theGlContext.operator->());
const TCollection_ExtendedString aMessage = TCollection_ExtendedString ("Error: Failed to compile ") +
(theType == GL_VERTEX_SHADER ? "vertex" : "fragment") + " shader object:\n" + aBuildLog;
- theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
- GL_DEBUG_TYPE_ERROR_ARB, 0, GL_DEBUG_SEVERITY_HIGH_ARB, aMessage);
+ theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
+ GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, aMessage);
aShader->Release (theGlContext.operator->());
+#ifdef RAY_TRACE_PRINT_INFO
+ std::cout << "Shader build log:\n" << aBuildLog << "\n";
+#endif
+
return Handle(OpenGl_ShaderObject)();
}
else if (theGlContext->caps->glslWarnings)
const TCollection_ExtendedString aMessage = TCollection_ExtendedString (theType == GL_VERTEX_SHADER ?
"Vertex" : "Fragment") + " shader was compiled with following warnings:\n" + aBuildLog;
- theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
- GL_DEBUG_TYPE_PORTABILITY_ARB, 0, GL_DEBUG_SEVERITY_LOW_ARB, aMessage);
+ theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
+ GL_DEBUG_TYPE_PORTABILITY, 0, GL_DEBUG_SEVERITY_LOW, aMessage);
}
+
+#ifdef RAY_TRACE_PRINT_INFO
+ std::cout << "Shader build log:\n" << aBuildLog << "\n";
+#endif
}
return aShader;
}
// =======================================================================
-// function : InitRaytraceResources
+// function : initProgram
+// purpose : Creates GLSL program from the given shader objects
+// =======================================================================
+Handle(OpenGl_ShaderProgram) OpenGl_View::initProgram (const Handle(OpenGl_Context)& theGlContext,
+ const Handle(OpenGl_ShaderObject)& theVertShader,
+ const Handle(OpenGl_ShaderObject)& theFragShader)
+{
+ Handle(OpenGl_ShaderProgram) aProgram = new OpenGl_ShaderProgram;
+
+ if (!aProgram->Create (theGlContext))
+ {
+ theVertShader->Release (theGlContext.operator->());
+
+ theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
+ GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, "Failed to create shader program");
+
+ return Handle(OpenGl_ShaderProgram)();
+ }
+
+ if (!aProgram->AttachShader (theGlContext, theVertShader)
+ || !aProgram->AttachShader (theGlContext, theFragShader))
+ {
+ theVertShader->Release (theGlContext.operator->());
+
+ theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
+ GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, "Failed to attach shader objects");
+
+ return Handle(OpenGl_ShaderProgram)();
+ }
+
+ aProgram->SetAttributeName (theGlContext, Graphic3d_TOA_POS, "occVertex");
+
+ TCollection_AsciiString aLinkLog;
+
+ if (!aProgram->Link (theGlContext))
+ {
+ aProgram->FetchInfoLog (theGlContext, aLinkLog);
+
+ const TCollection_ExtendedString aMessage = TCollection_ExtendedString (
+ "Failed to link shader program:\n") + aLinkLog;
+
+ theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
+ GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, aMessage);
+
+ return Handle(OpenGl_ShaderProgram)();
+ }
+ else if (theGlContext->caps->glslWarnings)
+ {
+ aProgram->FetchInfoLog (theGlContext, aLinkLog);
+ if (!aLinkLog.IsEmpty() && !aLinkLog.IsEqual ("No errors.\n"))
+ {
+ const TCollection_ExtendedString aMessage = TCollection_ExtendedString (
+ "Shader program was linked with following warnings:\n") + aLinkLog;
+
+ theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
+ GL_DEBUG_TYPE_PORTABILITY, 0, GL_DEBUG_SEVERITY_LOW, aMessage);
+ }
+ }
+
+ return aProgram;
+}
+
+// =======================================================================
+// function : initRaytraceResources
// purpose : Initializes OpenGL/GLSL shader programs
// =======================================================================
-Standard_Boolean OpenGl_View::initRaytraceResources (const Graphic3d_CView& theCView, const Handle(OpenGl_Context)& theGlContext)
+Standard_Boolean OpenGl_View::initRaytraceResources (const Standard_Integer theSizeX,
+ const Standard_Integer theSizeY,
+ const Handle(OpenGl_Context)& theGlContext)
{
if (myRaytraceInitStatus == OpenGl_RT_FAIL)
{
Standard_Boolean aToRebuildShaders = Standard_False;
+ if (myRenderParams.RebuildRayTracingShaders) // requires complete re-initialization
+ {
+ myRaytraceInitStatus = OpenGl_RT_NONE;
+ releaseRaytraceResources (theGlContext, Standard_True);
+ myRenderParams.RebuildRayTracingShaders = Standard_False; // clear rebuilding flag
+ }
+
if (myRaytraceInitStatus == OpenGl_RT_INIT)
{
if (!myIsRaytraceDataValid)
+ {
return Standard_True;
+ }
const Standard_Integer aRequiredStackSize =
- myRaytraceGeometry.HighLevelTreeDepth() + myRaytraceGeometry.BottomLevelTreeDepth();
+ myRaytraceGeometry.TopLevelTreeDepth() + myRaytraceGeometry.BotLevelTreeDepth();
if (myRaytraceParameters.StackSize < aRequiredStackSize)
{
}
}
- if (theCView.RenderParams.RaytracingDepth != myRaytraceParameters.NbBounces)
+ if (myRenderParams.RaytracingDepth != myRaytraceParameters.NbBounces
+ || myRenderParams.IsTransparentShadowEnabled != myRaytraceParameters.TransparentShadows
+ || myRenderParams.IsGlobalIlluminationEnabled != myRaytraceParameters.GlobalIllumination
+ || myRenderParams.TwoSidedBsdfModels != myRaytraceParameters.TwoSidedBsdfModels
+ || myRaytraceGeometry.HasTextures() != myRaytraceParameters.UseBindlessTextures)
+ {
+ myRaytraceParameters.NbBounces = myRenderParams.RaytracingDepth;
+ myRaytraceParameters.TransparentShadows = myRenderParams.IsTransparentShadowEnabled;
+ myRaytraceParameters.GlobalIllumination = myRenderParams.IsGlobalIlluminationEnabled;
+ myRaytraceParameters.TwoSidedBsdfModels = myRenderParams.TwoSidedBsdfModels;
+ myRaytraceParameters.UseBindlessTextures = myRaytraceGeometry.HasTextures();
+ aToRebuildShaders = Standard_True;
+ }
+
+ if (myRenderParams.AdaptiveScreenSampling != myRaytraceParameters.AdaptiveScreenSampling)
{
- myRaytraceParameters.NbBounces = theCView.RenderParams.RaytracingDepth;
+ myRaytraceParameters.AdaptiveScreenSampling = myRenderParams.AdaptiveScreenSampling;
+ if (myRenderParams.AdaptiveScreenSampling) // adaptive sampling was requested
+ {
+ if (!theGlContext->HasRayTracingAdaptiveSampling())
+ {
+ // disable the feature if it is not supported
+ myRaytraceParameters.AdaptiveScreenSampling = myRenderParams.AdaptiveScreenSampling = Standard_False;
+ theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_PORTABILITY, 0, GL_DEBUG_SEVERITY_LOW,
+ "Adaptive sampling not supported (OpenGL 4.4 or GL_NV_shader_atomic_float is missing)");
+ }
+ }
+
aToRebuildShaders = Standard_True;
}
+ myTileSampler.SetSize (myRenderParams, myRaytraceParameters.AdaptiveScreenSampling ? Graphic3d_Vec2i (theSizeX, theSizeY) : Graphic3d_Vec2i (0, 0));
- if (theCView.RenderParams.IsTransparentShadowEnabled != myRaytraceParameters.TransparentShadows)
+ const bool toEnableDof = !myCamera->IsOrthographic() && myRaytraceParameters.GlobalIllumination;
+ if (myRaytraceParameters.DepthOfField != toEnableDof)
{
- myRaytraceParameters.TransparentShadows = theCView.RenderParams.IsTransparentShadowEnabled;
+ myRaytraceParameters.DepthOfField = toEnableDof;
aToRebuildShaders = Standard_True;
}
+ if (myRenderParams.ToneMappingMethod != myRaytraceParameters.ToneMappingMethod)
+ {
+ myRaytraceParameters.ToneMappingMethod = myRenderParams.ToneMappingMethod;
+ aToRebuildShaders = true;
+ }
+
if (aToRebuildShaders)
{
-#ifdef RAY_TRACE_PRINT_INFO
- std::cout << "Info: Rebuild shaders with stack size: " << myRaytraceParameters.StackSize << std::endl;
-#endif
+ // Reject accumulated frames
+ myAccumFrames = 0;
- // Change state to force update all uniforms
+ // Environment map should be updated
myToUpdateEnvironmentMap = Standard_True;
- TCollection_AsciiString aPrefixString = generateShaderPrefix (theGlContext);
+ const TCollection_AsciiString aPrefixString = generateShaderPrefix (theGlContext);
#ifdef RAY_TRACE_PRINT_INFO
std::cout << "GLSL prefix string:" << std::endl << aPrefixString << std::endl;
myRaytraceShaderSource.SetPrefix (aPrefixString);
myPostFSAAShaderSource.SetPrefix (aPrefixString);
+ myOutImageShaderSource.SetPrefix (aPrefixString);
- if (!myRaytraceShader->LoadSource (theGlContext, myRaytraceShaderSource.Source())
- || !myPostFSAAShader->LoadSource (theGlContext, myPostFSAAShaderSource.Source()))
- {
- return safeFailBack ("Failed to load source into ray-tracing fragment shaders", theGlContext);
- }
-
- if (!myRaytraceShader->Compile (theGlContext)
- || !myPostFSAAShader->Compile (theGlContext))
+ if (!myRaytraceShader->LoadAndCompile (theGlContext, myRaytraceShaderSource.Source())
+ || !myPostFSAAShader->LoadAndCompile (theGlContext, myPostFSAAShaderSource.Source())
+ || !myOutImageShader->LoadAndCompile (theGlContext, myOutImageShaderSource.Source()))
{
return safeFailBack ("Failed to compile ray-tracing fragment shaders", theGlContext);
}
myRaytraceProgram->SetAttributeName (theGlContext, Graphic3d_TOA_POS, "occVertex");
myPostFSAAProgram->SetAttributeName (theGlContext, Graphic3d_TOA_POS, "occVertex");
+ myOutImageProgram->SetAttributeName (theGlContext, Graphic3d_TOA_POS, "occVertex");
+
if (!myRaytraceProgram->Link (theGlContext)
- || !myPostFSAAProgram->Link (theGlContext))
+ || !myPostFSAAProgram->Link (theGlContext)
+ || !myOutImageProgram->Link (theGlContext))
{
return safeFailBack ("Failed to initialize vertex attributes for ray-tracing program", theGlContext);
}
if (myRaytraceInitStatus == OpenGl_RT_NONE)
{
+ myAccumFrames = 0; // accumulation should be restarted
+
if (!theGlContext->IsGlGreaterEqual (3, 1))
{
return safeFailBack ("Ray-tracing requires OpenGL 3.1 and higher", theGlContext);
return safeFailBack ("Ray-tracing requires EXT_framebuffer_blit extension", theGlContext);
}
- myRaytraceParameters.NbBounces = theCView.RenderParams.RaytracingDepth;
-
- TCollection_AsciiString aFolder = Graphic3d_ShaderProgram::ShadersFolder();
-
- if (aFolder.IsEmpty())
- {
- return safeFailBack ("Failed to locate shaders directory", theGlContext);
- }
+ myRaytraceParameters.NbBounces = myRenderParams.RaytracingDepth;
+ const TCollection_AsciiString aShaderFolder = Graphic3d_ShaderProgram::ShadersFolder();
if (myIsRaytraceDataValid)
{
myRaytraceParameters.StackSize = Max (THE_DEFAULT_STACK_SIZE,
- myRaytraceGeometry.HighLevelTreeDepth() + myRaytraceGeometry.BottomLevelTreeDepth());
+ myRaytraceGeometry.TopLevelTreeDepth() + myRaytraceGeometry.BotLevelTreeDepth());
}
- TCollection_AsciiString aPrefixString = generateShaderPrefix (theGlContext);
+ const TCollection_AsciiString aPrefixString = generateShaderPrefix (theGlContext);
#ifdef RAY_TRACE_PRINT_INFO
std::cout << "GLSL prefix string:" << std::endl << aPrefixString << std::endl;
#endif
+ ShaderSource aBasicVertShaderSrc;
{
- Handle(OpenGl_ShaderObject) aBasicVertShader = initShader (
- GL_VERTEX_SHADER, ShaderSource (aFolder + "/RaytraceBase.vs"), theGlContext);
-
- if (aBasicVertShader.IsNull())
+ if (!aShaderFolder.IsEmpty())
{
- return safeFailBack ("Failed to initialize ray-trace vertex shader", theGlContext);
+ const TCollection_AsciiString aFiles[] = { aShaderFolder + "/RaytraceBase.vs", "" };
+ if (!aBasicVertShaderSrc.LoadFromFiles (aFiles))
+ {
+ return safeFailBack (aBasicVertShaderSrc.ErrorDescription(), theGlContext);
+ }
}
-
- TCollection_AsciiString aFiles[] = { aFolder + "/RaytraceBase.fs",
- aFolder + "/RaytraceRender.fs" };
-
- myRaytraceShaderSource.Load (aFiles, 2);
-
- myRaytraceShaderSource.SetPrefix (aPrefixString);
-
- myRaytraceShader = initShader (GL_FRAGMENT_SHADER, myRaytraceShaderSource, theGlContext);
-
- if (myRaytraceShader.IsNull())
+ else
{
- aBasicVertShader->Release (theGlContext.operator->());
-
- return safeFailBack ("Failed to initialize ray-trace fragment shader", theGlContext);
+ const TCollection_AsciiString aSrcShaders[] = { Shaders_RaytraceBase_vs, "" };
+ aBasicVertShaderSrc.LoadFromStrings (aSrcShaders);
}
+ }
- myRaytraceProgram = new OpenGl_ShaderProgram;
-
- if (!myRaytraceProgram->Create (theGlContext))
+ {
+ if (!aShaderFolder.IsEmpty())
{
- aBasicVertShader->Release (theGlContext.operator->());
+ const TCollection_AsciiString aFiles[] = { aShaderFolder + "/RaytraceBase.fs",
+ aShaderFolder + "/PathtraceBase.fs",
+ aShaderFolder + "/RaytraceRender.fs",
+ "" };
+ if (!myRaytraceShaderSource.LoadFromFiles (aFiles, aPrefixString))
+ {
+ return safeFailBack (myRaytraceShaderSource.ErrorDescription(), theGlContext);
+ }
+ }
+ else
+ {
+ const TCollection_AsciiString aSrcShaders[] = { Shaders_RaytraceBase_fs,
+ Shaders_PathtraceBase_fs,
+ Shaders_RaytraceRender_fs,
+ "" };
+ myRaytraceShaderSource.LoadFromStrings (aSrcShaders, aPrefixString);
+ }
- return safeFailBack ("Failed to create ray-trace shader program", theGlContext);
+ Handle(OpenGl_ShaderObject) aBasicVertShader = initShader (GL_VERTEX_SHADER, aBasicVertShaderSrc, theGlContext);
+ if (aBasicVertShader.IsNull())
+ {
+ return safeFailBack ("Failed to initialize ray-trace vertex shader", theGlContext);
}
- if (!myRaytraceProgram->AttachShader (theGlContext, aBasicVertShader)
- || !myRaytraceProgram->AttachShader (theGlContext, myRaytraceShader))
+ myRaytraceShader = initShader (GL_FRAGMENT_SHADER, myRaytraceShaderSource, theGlContext);
+ if (myRaytraceShader.IsNull())
{
aBasicVertShader->Release (theGlContext.operator->());
-
- return safeFailBack ("Failed to attach ray-trace shader objects", theGlContext);
+ return safeFailBack ("Failed to initialize ray-trace fragment shader", theGlContext);
}
- myRaytraceProgram->SetAttributeName (theGlContext, Graphic3d_TOA_POS, "occVertex");
-
- TCollection_AsciiString aLinkLog;
-
- if (!myRaytraceProgram->Link (theGlContext))
+ myRaytraceProgram = initProgram (theGlContext, aBasicVertShader, myRaytraceShader);
+ if (myRaytraceProgram.IsNull())
{
- myRaytraceProgram->FetchInfoLog (theGlContext, aLinkLog);
-
- return safeFailBack (TCollection_ExtendedString (
- "Failed to link ray-trace shader program:\n") + aLinkLog, theGlContext);
+ return safeFailBack ("Failed to initialize ray-trace shader program", theGlContext);
}
- else if (theGlContext->caps->glslWarnings)
- {
- myRaytraceProgram->FetchInfoLog (theGlContext, aLinkLog);
+ }
- if (!aLinkLog.IsEmpty() && !aLinkLog.IsEqual ("No errors.\n"))
+ {
+ if (!aShaderFolder.IsEmpty())
+ {
+ const TCollection_AsciiString aFiles[] = { aShaderFolder + "/RaytraceBase.fs", aShaderFolder + "/RaytraceSmooth.fs", "" };
+ if (!myPostFSAAShaderSource.LoadFromFiles (aFiles, aPrefixString))
{
- const TCollection_ExtendedString aMessage = TCollection_ExtendedString (
- "Ray-trace shader program was linked with following warnings:\n") + aLinkLog;
-
- theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
- GL_DEBUG_TYPE_PORTABILITY_ARB, 0, GL_DEBUG_SEVERITY_LOW_ARB, aMessage);
+ return safeFailBack (myPostFSAAShaderSource.ErrorDescription(), theGlContext);
}
}
- }
-
- {
- Handle(OpenGl_ShaderObject) aBasicVertShader = initShader (
- GL_VERTEX_SHADER, ShaderSource (aFolder + "/RaytraceBase.vs"), theGlContext);
+ else
+ {
+ const TCollection_AsciiString aSrcShaders[] = { Shaders_RaytraceBase_fs, Shaders_RaytraceSmooth_fs, "" };
+ myPostFSAAShaderSource.LoadFromStrings (aSrcShaders, aPrefixString);
+ }
+ Handle(OpenGl_ShaderObject) aBasicVertShader = initShader (GL_VERTEX_SHADER, aBasicVertShaderSrc, theGlContext);
if (aBasicVertShader.IsNull())
{
return safeFailBack ("Failed to initialize FSAA vertex shader", theGlContext);
}
- TCollection_AsciiString aFiles[] = { aFolder + "/RaytraceBase.fs",
- aFolder + "/RaytraceSmooth.fs" };
-
- myPostFSAAShaderSource.Load (aFiles, 2);
-
- myPostFSAAShaderSource.SetPrefix (aPrefixString);
-
myPostFSAAShader = initShader (GL_FRAGMENT_SHADER, myPostFSAAShaderSource, theGlContext);
-
if (myPostFSAAShader.IsNull())
{
aBasicVertShader->Release (theGlContext.operator->());
-
return safeFailBack ("Failed to initialize FSAA fragment shader", theGlContext);
}
- myPostFSAAProgram = new OpenGl_ShaderProgram;
-
- if (!myPostFSAAProgram->Create (theGlContext))
+ myPostFSAAProgram = initProgram (theGlContext, aBasicVertShader, myPostFSAAShader);
+ if (myPostFSAAProgram.IsNull())
{
- aBasicVertShader->Release (theGlContext.operator->());
-
- return safeFailBack ("Failed to create FSAA shader program", theGlContext);
+ return safeFailBack ("Failed to initialize FSAA shader program", theGlContext);
}
+ }
- if (!myPostFSAAProgram->AttachShader (theGlContext, aBasicVertShader)
- || !myPostFSAAProgram->AttachShader (theGlContext, myPostFSAAShader))
+ {
+ if (!aShaderFolder.IsEmpty())
{
- aBasicVertShader->Release (theGlContext.operator->());
-
- return safeFailBack ("Failed to attach FSAA shader objects", theGlContext);
+ const TCollection_AsciiString aFiles[] = { aShaderFolder + "/Display.fs", "" };
+ if (!myOutImageShaderSource.LoadFromFiles (aFiles, aPrefixString))
+ {
+ return safeFailBack (myOutImageShaderSource.ErrorDescription(), theGlContext);
+ }
}
-
- myPostFSAAProgram->SetAttributeName (theGlContext, Graphic3d_TOA_POS, "occVertex");
-
- TCollection_AsciiString aLinkLog;
-
- if (!myPostFSAAProgram->Link (theGlContext))
+ else
{
- myPostFSAAProgram->FetchInfoLog (theGlContext, aLinkLog);
-
- return safeFailBack (TCollection_ExtendedString (
- "Failed to link FSAA shader program:\n") + aLinkLog, theGlContext);
+ const TCollection_AsciiString aSrcShaders[] = { Shaders_Display_fs, "" };
+ myOutImageShaderSource.LoadFromStrings (aSrcShaders, aPrefixString);
}
- else if (theGlContext->caps->glslWarnings)
+
+ Handle(OpenGl_ShaderObject) aBasicVertShader = initShader (GL_VERTEX_SHADER, aBasicVertShaderSrc, theGlContext);
+ if (aBasicVertShader.IsNull())
{
- myPostFSAAProgram->FetchInfoLog (theGlContext, aLinkLog);
+ return safeFailBack ("Failed to set vertex shader source", theGlContext);
+ }
- if (!aLinkLog.IsEmpty() && !aLinkLog.IsEqual ("No errors.\n"))
- {
- const TCollection_ExtendedString aMessage = TCollection_ExtendedString (
- "FSAA shader program was linked with following warnings:\n") + aLinkLog;
+ myOutImageShader = initShader (GL_FRAGMENT_SHADER, myOutImageShaderSource, theGlContext);
+ if (myOutImageShader.IsNull())
+ {
+ aBasicVertShader->Release (theGlContext.operator->());
+ return safeFailBack ("Failed to set display fragment shader source", theGlContext);
+ }
- theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
- GL_DEBUG_TYPE_PORTABILITY_ARB, 0, GL_DEBUG_SEVERITY_LOW_ARB, aMessage);
- }
+ myOutImageProgram = initProgram (theGlContext, aBasicVertShader, myOutImageShader);
+ if (myOutImageProgram.IsNull())
+ {
+ return safeFailBack ("Failed to initialize display shader program", theGlContext);
}
}
}
aShaderProgram->SetSampler (theGlContext,
"uRaytraceLightSrcTexture", OpenGl_RT_RaytraceLightSrcTexture);
- aShaderProgram->SetSampler (theGlContext,
- "uOpenGlColorTexture", OpenGl_RT_OpenGlColorTexture);
- aShaderProgram->SetSampler (theGlContext,
- "uOpenGlDepthTexture", OpenGl_RT_OpenGlDepthTexture);
-
if (anIndex == 1)
{
aShaderProgram->SetSampler (theGlContext,
- "uFSAAInputTexture", OpenGl_RT_FSAAInputTexture);
+ "uFSAAInputTexture", OpenGl_RT_FsaaInputTexture);
+ }
+ else
+ {
+ aShaderProgram->SetSampler (theGlContext,
+ "uAccumTexture", OpenGl_RT_PrevAccumTexture);
}
myUniformLocations[anIndex][OpenGl_RT_aPosition] =
aShaderProgram->GetUniformLocation (theGlContext, "uDirectLT");
myUniformLocations[anIndex][OpenGl_RT_uDirectRT] =
aShaderProgram->GetUniformLocation (theGlContext, "uDirectRT");
+ myUniformLocations[anIndex][OpenGl_RT_uViewPrMat] =
+ aShaderProgram->GetUniformLocation (theGlContext, "uViewMat");
myUniformLocations[anIndex][OpenGl_RT_uUnviewMat] =
aShaderProgram->GetUniformLocation (theGlContext, "uUnviewMat");
aShaderProgram->GetUniformLocation (theGlContext, "uOffsetY");
myUniformLocations[anIndex][OpenGl_RT_uSamples] =
aShaderProgram->GetUniformLocation (theGlContext, "uSamples");
+
+ myUniformLocations[anIndex][OpenGl_RT_uTexSamplersArray] =
+ aShaderProgram->GetUniformLocation (theGlContext, "uTextureSamplers");
+
+ myUniformLocations[anIndex][OpenGl_RT_uShadowsEnabled] =
+ aShaderProgram->GetUniformLocation (theGlContext, "uShadowsEnabled");
+ myUniformLocations[anIndex][OpenGl_RT_uReflectEnabled] =
+ aShaderProgram->GetUniformLocation (theGlContext, "uReflectEnabled");
+ myUniformLocations[anIndex][OpenGl_RT_uSphereMapEnabled] =
+ aShaderProgram->GetUniformLocation (theGlContext, "uSphereMapEnabled");
+ myUniformLocations[anIndex][OpenGl_RT_uSphereMapForBack] =
+ aShaderProgram->GetUniformLocation (theGlContext, "uSphereMapForBack");
+ myUniformLocations[anIndex][OpenGl_RT_uBlockedRngEnabled] =
+ aShaderProgram->GetUniformLocation (theGlContext, "uBlockedRngEnabled");
+
myUniformLocations[anIndex][OpenGl_RT_uWinSizeX] =
aShaderProgram->GetUniformLocation (theGlContext, "uWinSizeX");
myUniformLocations[anIndex][OpenGl_RT_uWinSizeY] =
aShaderProgram->GetUniformLocation (theGlContext, "uWinSizeY");
- myUniformLocations[anIndex][OpenGl_RT_uTextures] =
- aShaderProgram->GetUniformLocation (theGlContext, "uTextureSamplers");
+ myUniformLocations[anIndex][OpenGl_RT_uAccumSamples] =
+ aShaderProgram->GetUniformLocation (theGlContext, "uAccumSamples");
+ myUniformLocations[anIndex][OpenGl_RT_uFrameRndSeed] =
+ aShaderProgram->GetUniformLocation (theGlContext, "uFrameRndSeed");
- myUniformLocations[anIndex][OpenGl_RT_uShadEnabled] =
- aShaderProgram->GetUniformLocation (theGlContext, "uShadowsEnable");
- myUniformLocations[anIndex][OpenGl_RT_uReflEnabled] =
- aShaderProgram->GetUniformLocation (theGlContext, "uReflectionsEnable");
- myUniformLocations[anIndex][OpenGl_RT_uEnvMapEnable] =
- aShaderProgram->GetUniformLocation (theGlContext, "uEnvironmentEnable");
+ myUniformLocations[anIndex][OpenGl_RT_uRenderImage] =
+ aShaderProgram->GetUniformLocation (theGlContext, "uRenderImage");
+ myUniformLocations[anIndex][OpenGl_RT_uOffsetImage] =
+ aShaderProgram->GetUniformLocation (theGlContext, "uOffsetImage");
+ myUniformLocations[anIndex][OpenGl_RT_uTileSize] =
+ aShaderProgram->GetUniformLocation (theGlContext, "uTileSize");
+ myUniformLocations[anIndex][OpenGl_RT_uVarianceScaleFactor] =
+ aShaderProgram->GetUniformLocation (theGlContext, "uVarianceScaleFactor");
+
+ myUniformLocations[anIndex][OpenGl_RT_uBackColorTop] =
+ aShaderProgram->GetUniformLocation (theGlContext, "uBackColorTop");
+ myUniformLocations[anIndex][OpenGl_RT_uBackColorBot] =
+ aShaderProgram->GetUniformLocation (theGlContext, "uBackColorBot");
+
+ myUniformLocations[anIndex][OpenGl_RT_uMaxRadiance] =
+ aShaderProgram->GetUniformLocation (theGlContext, "uMaxRadiance");
}
+ theGlContext->BindProgram (myOutImageProgram);
+
+ myOutImageProgram->SetSampler (theGlContext,
+ "uInputTexture", OpenGl_RT_PrevAccumTexture);
+
+ myOutImageProgram->SetSampler (theGlContext,
+ "uDepthTexture", OpenGl_RT_RaytraceDepthTexture);
+
theGlContext->BindProgram (NULL);
}
return myRaytraceInitStatus == OpenGl_RT_INIT;
}
- if (myRaytraceFBO1.IsNull())
- {
- myRaytraceFBO1 = new OpenGl_FrameBuffer;
- }
-
- if (myRaytraceFBO2.IsNull())
- {
- myRaytraceFBO2 = new OpenGl_FrameBuffer;
- }
-
const GLfloat aVertices[] = { -1.f, -1.f, 0.f,
-1.f, 1.f, 0.f,
1.f, 1.f, 0.f,
}
// =======================================================================
-// function : NullifyResource
-// purpose :
+// function : nullifyResource
+// purpose : Releases OpenGL resource
// =======================================================================
-inline void NullifyResource (const Handle(OpenGl_Context)& theGlContext,
- Handle(OpenGl_Resource)& theResource)
+template <class T>
+inline void nullifyResource (const Handle(OpenGl_Context)& theGlContext, Handle(T)& theResource)
{
if (!theResource.IsNull())
{
}
// =======================================================================
-// function : ReleaseRaytraceResources
+// function : releaseRaytraceResources
// purpose : Releases OpenGL/GLSL shader programs
// =======================================================================
-void OpenGl_View::releaseRaytraceResources (const Handle(OpenGl_Context)& theGlContext)
+void OpenGl_View::releaseRaytraceResources (const Handle(OpenGl_Context)& theGlContext, const Standard_Boolean theToRebuild)
{
- NullifyResource (theGlContext, myOpenGlFBO);
- NullifyResource (theGlContext, myRaytraceFBO1);
- NullifyResource (theGlContext, myRaytraceFBO2);
+ // release shader resources
+ nullifyResource (theGlContext, myRaytraceShader);
+ nullifyResource (theGlContext, myPostFSAAShader);
+
+ nullifyResource (theGlContext, myRaytraceProgram);
+ nullifyResource (theGlContext, myPostFSAAProgram);
+ nullifyResource (theGlContext, myOutImageProgram);
+
+ if (!theToRebuild) // complete release
+ {
+ myRaytraceFBO1[0]->Release (theGlContext.operator->());
+ myRaytraceFBO1[1]->Release (theGlContext.operator->());
+ myRaytraceFBO2[0]->Release (theGlContext.operator->());
+ myRaytraceFBO2[1]->Release (theGlContext.operator->());
- NullifyResource (theGlContext, myRaytraceShader);
- NullifyResource (theGlContext, myPostFSAAShader);
+ nullifyResource (theGlContext, myRaytraceOutputTexture[0]);
+ nullifyResource (theGlContext, myRaytraceOutputTexture[1]);
- NullifyResource (theGlContext, myRaytraceProgram);
- NullifyResource (theGlContext, myPostFSAAProgram);
+ nullifyResource (theGlContext, myRaytraceTileOffsetsTexture[0]);
+ nullifyResource (theGlContext, myRaytraceTileOffsetsTexture[1]);
+ nullifyResource (theGlContext, myRaytraceVisualErrorTexture[0]);
+ nullifyResource (theGlContext, myRaytraceVisualErrorTexture[1]);
- NullifyResource (theGlContext, mySceneNodeInfoTexture);
- NullifyResource (theGlContext, mySceneMinPointTexture);
- NullifyResource (theGlContext, mySceneMaxPointTexture);
+ nullifyResource (theGlContext, mySceneNodeInfoTexture);
+ nullifyResource (theGlContext, mySceneMinPointTexture);
+ nullifyResource (theGlContext, mySceneMaxPointTexture);
- NullifyResource (theGlContext, myGeometryVertexTexture);
- NullifyResource (theGlContext, myGeometryNormalTexture);
- NullifyResource (theGlContext, myGeometryTexCrdTexture);
- NullifyResource (theGlContext, myGeometryTriangTexture);
- NullifyResource (theGlContext, mySceneTransformTexture);
+ nullifyResource (theGlContext, myGeometryVertexTexture);
+ nullifyResource (theGlContext, myGeometryNormalTexture);
+ nullifyResource (theGlContext, myGeometryTexCrdTexture);
+ nullifyResource (theGlContext, myGeometryTriangTexture);
+ nullifyResource (theGlContext, mySceneTransformTexture);
- NullifyResource (theGlContext, myRaytraceLightSrcTexture);
- NullifyResource (theGlContext, myRaytraceMaterialTexture);
+ nullifyResource (theGlContext, myRaytraceLightSrcTexture);
+ nullifyResource (theGlContext, myRaytraceMaterialTexture);
- if (myRaytraceScreenQuad.IsValid())
- myRaytraceScreenQuad.Release (theGlContext.operator->());
+ myRaytraceGeometry.ReleaseResources (theGlContext);
+
+ if (myRaytraceScreenQuad.IsValid ())
+ {
+ myRaytraceScreenQuad.Release (theGlContext.operator->());
+ }
+ }
}
// =======================================================================
-// function : ResizeRaytraceBuffers
-// purpose : Resizes OpenGL frame buffers
+// function : updateRaytraceBuffers
+// purpose : Updates auxiliary OpenGL frame buffers.
// =======================================================================
-Standard_Boolean OpenGl_View::resizeRaytraceBuffers (const Standard_Integer theSizeX,
+Standard_Boolean OpenGl_View::updateRaytraceBuffers (const Standard_Integer theSizeX,
const Standard_Integer theSizeY,
const Handle(OpenGl_Context)& theGlContext)
{
- if (myRaytraceFBO1->GetVPSizeX() != theSizeX
- || myRaytraceFBO1->GetVPSizeY() != theSizeY)
+ // Auxiliary buffers are not used
+ if (!myRaytraceParameters.GlobalIllumination && !myRenderParams.IsAntialiasingEnabled)
{
- myRaytraceFBO1->Init (theGlContext, theSizeX, theSizeY);
- myRaytraceFBO2->Init (theGlContext, theSizeX, theSizeY);
+ myRaytraceFBO1[0]->Release (theGlContext.operator->());
+ myRaytraceFBO2[0]->Release (theGlContext.operator->());
+ myRaytraceFBO1[1]->Release (theGlContext.operator->());
+ myRaytraceFBO2[1]->Release (theGlContext.operator->());
+
+ return Standard_True;
+ }
+
+ if (myRaytraceParameters.AdaptiveScreenSampling)
+ {
+ Graphic3d_Vec2i aMaxViewport = myTileSampler.OffsetTilesViewportMax().cwiseMax (Graphic3d_Vec2i (theSizeX, theSizeY));
+ myRaytraceFBO1[0]->InitLazy (theGlContext, aMaxViewport.x(), aMaxViewport.y(), GL_RGBA32F, myFboDepthFormat);
+ myRaytraceFBO2[0]->InitLazy (theGlContext, aMaxViewport.x(), aMaxViewport.y(), GL_RGBA32F, myFboDepthFormat);
+ if (myRaytraceFBO1[1]->IsValid()) // second FBO not needed
+ {
+ myRaytraceFBO1[1]->Release (theGlContext.operator->());
+ myRaytraceFBO2[1]->Release (theGlContext.operator->());
+ }
}
+ for (int aViewIter = 0; aViewIter < 2; ++aViewIter)
+ {
+ if (myRaytraceTileOffsetsTexture[aViewIter].IsNull())
+ {
+ myRaytraceOutputTexture[aViewIter] = new OpenGl_Texture();
+ myRaytraceVisualErrorTexture[aViewIter] = new OpenGl_Texture();
+ myRaytraceTileOffsetsTexture[aViewIter] = new OpenGl_Texture();
+ }
+
+ if (aViewIter == 1
+ && myCamera->ProjectionType() != Graphic3d_Camera::Projection_Stereo)
+ {
+ myRaytraceFBO1[1]->Release (theGlContext.operator->());
+ myRaytraceFBO2[1]->Release (theGlContext.operator->());
+ myRaytraceOutputTexture[1]->Release (theGlContext.operator->());
+ myRaytraceVisualErrorTexture[1]->Release (theGlContext.operator->());
+ myRaytraceTileOffsetsTexture[1]->Release (theGlContext.operator->());
+ continue;
+ }
+
+ if (myRaytraceParameters.AdaptiveScreenSampling)
+ {
+ if (myRaytraceOutputTexture[aViewIter]->SizeX() / 3 == theSizeX
+ && myRaytraceOutputTexture[aViewIter]->SizeY() / 2 == theSizeY
+ && myRaytraceVisualErrorTexture[aViewIter]->SizeX() == myTileSampler.NbTilesX()
+ && myRaytraceVisualErrorTexture[aViewIter]->SizeY() == myTileSampler.NbTilesY())
+ {
+ continue;
+ }
+
+ myAccumFrames = 0;
+
+ // Due to limitations of OpenGL image load-store extension
+ // atomic operations are supported only for single-channel
+ // images, so we define GL_R32F image. It is used as array
+ // of 6D floating point vectors:
+ // 0 - R color channel
+ // 1 - G color channel
+ // 2 - B color channel
+ // 3 - hit time transformed into OpenGL NDC space
+ // 4 - luminance accumulated for odd samples only
+ myRaytraceOutputTexture[aViewIter]->InitRectangle (theGlContext, theSizeX * 3, theSizeY * 2, OpenGl_TextureFormat::Create<GLfloat, 1>());
+
+ // workaround for some NVIDIA drivers
+ myRaytraceVisualErrorTexture[aViewIter]->Release (theGlContext.operator->());
+ myRaytraceVisualErrorTexture[aViewIter]->Init (theGlContext, GL_R32I, GL_RED_INTEGER, GL_INT,
+ myTileSampler.NbTilesX(), myTileSampler.NbTilesY(), Graphic3d_TOT_2D);
+ }
+ else // non-adaptive mode
+ {
+ if (myRaytraceFBO1[aViewIter]->GetSizeX() != theSizeX
+ || myRaytraceFBO1[aViewIter]->GetSizeY() != theSizeY)
+ {
+ myAccumFrames = 0; // accumulation should be restarted
+ }
+
+ myRaytraceFBO1[aViewIter]->InitLazy (theGlContext, theSizeX, theSizeY, GL_RGBA32F, myFboDepthFormat);
+ myRaytraceFBO2[aViewIter]->InitLazy (theGlContext, theSizeX, theSizeY, GL_RGBA32F, myFboDepthFormat);
+ }
+ }
return Standard_True;
}
// =======================================================================
-// function : UpdateCamera
+// function : updateCamera
// purpose : Generates viewing rays for corners of screen quad
// =======================================================================
void OpenGl_View::updateCamera (const OpenGl_Mat4& theOrientation,
const OpenGl_Mat4& theViewMapping,
OpenGl_Vec3* theOrigins,
OpenGl_Vec3* theDirects,
+ OpenGl_Mat4& theViewPr,
OpenGl_Mat4& theUnview)
{
- // compute inverse model-view-projection matrix
- (theViewMapping * theOrientation).Inverted (theUnview);
+ // compute view-projection matrix
+ theViewPr = theViewMapping * theOrientation;
+
+ // compute inverse view-projection matrix
+ theViewPr.Inverted (theUnview);
Standard_Integer aOriginIndex = 0;
Standard_Integer aDirectIndex = 0;
{
OpenGl_Vec4 aOrigin (GLfloat(aX),
GLfloat(aY),
- -1.0f,
+ -1.0f,
1.0f);
aOrigin = theUnview * aOrigin;
aDirect = aDirect - aOrigin;
- GLdouble aInvLen = 1.0 / sqrt (aDirect.x() * aDirect.x() +
- aDirect.y() * aDirect.y() +
- aDirect.z() * aDirect.z());
-
theOrigins[aOriginIndex++] = OpenGl_Vec3 (static_cast<GLfloat> (aOrigin.x()),
static_cast<GLfloat> (aOrigin.y()),
static_cast<GLfloat> (aOrigin.z()));
- theDirects[aDirectIndex++] = OpenGl_Vec3 (static_cast<GLfloat> (aDirect.x() * aInvLen),
- static_cast<GLfloat> (aDirect.y() * aInvLen),
- static_cast<GLfloat> (aDirect.z() * aInvLen));
+ theDirects[aDirectIndex++] = OpenGl_Vec3 (static_cast<GLfloat> (aDirect.x()),
+ static_cast<GLfloat> (aDirect.y()),
+ static_cast<GLfloat> (aDirect.z()));
}
}
}
// =======================================================================
-// function : UploadRaytraceData
+// function : updatePerspCameraPT
+// purpose : Generates viewing rays (path tracing, perspective camera)
+// =======================================================================
+void OpenGl_View::updatePerspCameraPT (const OpenGl_Mat4& theOrientation,
+ const OpenGl_Mat4& theViewMapping,
+ Graphic3d_Camera::Projection theProjection,
+ OpenGl_Mat4& theViewPr,
+ OpenGl_Mat4& theUnview,
+ const int theWinSizeX,
+ const int theWinSizeY)
+{
+ // compute view-projection matrix
+ theViewPr = theViewMapping * theOrientation;
+
+ // compute inverse view-projection matrix
+ theViewPr.Inverted(theUnview);
+
+ // get camera stereo params
+ float anIOD = myCamera->GetIODType() == Graphic3d_Camera::IODType_Relative
+ ? static_cast<float> (myCamera->IOD() * myCamera->Distance())
+ : static_cast<float> (myCamera->IOD());
+
+ float aZFocus = myCamera->ZFocusType() == Graphic3d_Camera::FocusType_Relative
+ ? static_cast<float> (myCamera->ZFocus() * myCamera->Distance())
+ : static_cast<float> (myCamera->ZFocus());
+
+ // get camera view vectors
+ const gp_Pnt anOrig = myCamera->Eye();
+
+ myEyeOrig = OpenGl_Vec3 (static_cast<float> (anOrig.X()),
+ static_cast<float> (anOrig.Y()),
+ static_cast<float> (anOrig.Z()));
+
+ const gp_Dir aView = myCamera->Direction();
+
+ OpenGl_Vec3 anEyeViewMono = OpenGl_Vec3 (static_cast<float> (aView.X()),
+ static_cast<float> (aView.Y()),
+ static_cast<float> (aView.Z()));
+
+ const gp_Dir anUp = myCamera->Up();
+
+ myEyeVert = OpenGl_Vec3 (static_cast<float> (anUp.X()),
+ static_cast<float> (anUp.Y()),
+ static_cast<float> (anUp.Z()));
+
+ myEyeSide = OpenGl_Vec3::Cross (anEyeViewMono, myEyeVert);
+
+ const double aScaleY = tan (myCamera->FOVy() / 360 * M_PI);
+ const double aScaleX = theWinSizeX * aScaleY / theWinSizeY;
+
+ myEyeSize = OpenGl_Vec2 (static_cast<float> (aScaleX),
+ static_cast<float> (aScaleY));
+
+ if (theProjection == Graphic3d_Camera::Projection_Perspective)
+ {
+ myEyeView = anEyeViewMono;
+ }
+ else // stereo camera
+ {
+ // compute z-focus point
+ OpenGl_Vec3 aZFocusPoint = myEyeOrig + anEyeViewMono * aZFocus;
+
+ // compute stereo camera shift
+ float aDx = theProjection == Graphic3d_Camera::Projection_MonoRightEye ? 0.5f * anIOD : -0.5f * anIOD;
+ myEyeOrig += myEyeSide.Normalized() * aDx;
+
+ // estimate new camera direction vector and correct its length
+ myEyeView = (aZFocusPoint - myEyeOrig).Normalized();
+ myEyeView *= 1.f / anEyeViewMono.Dot (myEyeView);
+ }
+}
+
+// =======================================================================
+// function : uploadRaytraceData
// purpose : Uploads ray-trace data to the GPU
// =======================================================================
Standard_Boolean OpenGl_View::uploadRaytraceData (const Handle(OpenGl_Context)& theGlContext)
return Standard_False;
}
+ myAccumFrames = 0; // accumulation should be restarted
+
/////////////////////////////////////////////////////////////////////////////
// Prepare OpenGL textures
/////////////////////////////////////////////////////////////////////////////
// Create OpenGL BVH buffers
- if (mySceneNodeInfoTexture.IsNull()) // create scene BVH buffers
+ if (mySceneNodeInfoTexture.IsNull()) // create scene BVH buffers
{
mySceneNodeInfoTexture = new OpenGl_TextureBufferArb;
mySceneMinPointTexture = new OpenGl_TextureBufferArb;
}
}
- if (myGeometryVertexTexture.IsNull()) // create geometry buffers
+ if (myGeometryVertexTexture.IsNull()) // create geometry buffers
{
myGeometryVertexTexture = new OpenGl_TextureBufferArb;
myGeometryNormalTexture = new OpenGl_TextureBufferArb;
OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
myRaytraceGeometry.Objects().ChangeValue (anElemIndex).operator->());
- const BVH_Transform<Standard_ShortReal, 4>* aTransform =
- dynamic_cast<const BVH_Transform<Standard_ShortReal, 4>* > (aTriangleSet->Properties().operator->());
-
+ const BVH_Transform<Standard_ShortReal, 4>* aTransform = dynamic_cast<const BVH_Transform<Standard_ShortReal, 4>* > (aTriangleSet->Properties().get());
Standard_ASSERT_RETURN (aTransform != NULL,
"OpenGl_TriangleSet does not contain transform", Standard_False);
aTotalVerticesNb += aTriangleSet->Vertices.size();
aTotalElementsNb += aTriangleSet->Elements.size();
- Standard_ASSERT_RETURN (!aTriangleSet->BVH().IsNull(),
+ Standard_ASSERT_RETURN (!aTriangleSet->QuadBVH().IsNull(),
"Error: Failed to get bottom-level BVH of OpenGL element", Standard_False);
- aTotalBVHNodesNb += aTriangleSet->BVH()->NodeInfoBuffer().size();
+ aTotalBVHNodesNb += aTriangleSet->QuadBVH()->NodeInfoBuffer().size();
}
- aTotalBVHNodesNb += myRaytraceGeometry.BVH()->NodeInfoBuffer().size();
+ aTotalBVHNodesNb += myRaytraceGeometry.QuadBVH()->NodeInfoBuffer().size();
if (aTotalBVHNodesNb != 0)
{
return Standard_False;
}
- const NCollection_Handle<BVH_Tree<Standard_ShortReal, 3> >& aBVH = myRaytraceGeometry.BVH();
+ const QuadBvhHandle& aBVH = myRaytraceGeometry.QuadBVH();
if (aBVH->Length() > 0)
{
Standard_ASSERT_RETURN (aBVHOffset != OpenGl_RaytraceGeometry::INVALID_OFFSET,
"Error: Failed to get offset for bottom-level BVH", Standard_False);
- const Standard_Integer aBvhBuffersSize = aTriangleSet->BVH()->Length();
+ const Standard_Integer aBvhBuffersSize = aTriangleSet->QuadBVH()->Length();
if (aBvhBuffersSize != 0)
{
aResult &= mySceneNodeInfoTexture->SubData (theGlContext, aBVHOffset, aBvhBuffersSize,
- reinterpret_cast<const GLuint*> (&aTriangleSet->BVH()->NodeInfoBuffer().front()));
+ reinterpret_cast<const GLuint*> (&aTriangleSet->QuadBVH()->NodeInfoBuffer().front()));
aResult &= mySceneMinPointTexture->SubData (theGlContext, aBVHOffset, aBvhBuffersSize,
- reinterpret_cast<const GLfloat*> (&aTriangleSet->BVH()->MinPointBuffer().front()));
+ reinterpret_cast<const GLfloat*> (&aTriangleSet->QuadBVH()->MinPointBuffer().front()));
aResult &= mySceneMaxPointTexture->SubData (theGlContext, aBVHOffset, aBvhBuffersSize,
- reinterpret_cast<const GLfloat*> (&aTriangleSet->BVH()->MaxPointBuffer().front()));
+ reinterpret_cast<const GLfloat*> (&aTriangleSet->QuadBVH()->MaxPointBuffer().front()));
if (!aResult)
{
if (myRaytraceGeometry.Materials.size() != 0)
{
aResult &= myRaytraceMaterialTexture->Init (theGlContext, 4,
- GLsizei (myRaytraceGeometry.Materials.size() * 11), myRaytraceGeometry.Materials.front().Packed());
+ GLsizei (myRaytraceGeometry.Materials.size() * 19), myRaytraceGeometry.Materials.front().Packed());
if (!aResult)
{
#ifdef RAY_TRACE_PRINT_INFO
- Standard_ShortReal aMemUsed = 0.f;
+ Standard_ShortReal aMemTrgUsed = 0.f;
+ Standard_ShortReal aMemBvhUsed = 0.f;
for (Standard_Integer anElemIdx = 0; anElemIdx < myRaytraceGeometry.Size(); ++anElemIdx)
{
- OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
- myRaytraceGeometry.Objects().ChangeValue (anElemIdx).operator->());
+ OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (myRaytraceGeometry.Objects()(anElemIdx).get());
- aMemUsed += static_cast<Standard_ShortReal> (
+ aMemTrgUsed += static_cast<Standard_ShortReal> (
aTriangleSet->Vertices.size() * sizeof (BVH_Vec3f));
- aMemUsed += static_cast<Standard_ShortReal> (
+ aMemTrgUsed += static_cast<Standard_ShortReal> (
aTriangleSet->Normals.size() * sizeof (BVH_Vec3f));
- aMemUsed += static_cast<Standard_ShortReal> (
+ aMemTrgUsed += static_cast<Standard_ShortReal> (
aTriangleSet->TexCrds.size() * sizeof (BVH_Vec2f));
- aMemUsed += static_cast<Standard_ShortReal> (
+ aMemTrgUsed += static_cast<Standard_ShortReal> (
aTriangleSet->Elements.size() * sizeof (BVH_Vec4i));
- aMemUsed += static_cast<Standard_ShortReal> (
- aTriangleSet->BVH()->NodeInfoBuffer().size() * sizeof (BVH_Vec4i));
- aMemUsed += static_cast<Standard_ShortReal> (
- aTriangleSet->BVH()->MinPointBuffer().size() * sizeof (BVH_Vec3f));
- aMemUsed += static_cast<Standard_ShortReal> (
- aTriangleSet->BVH()->MaxPointBuffer().size() * sizeof (BVH_Vec3f));
+ aMemBvhUsed += static_cast<Standard_ShortReal> (
+ aTriangleSet->QuadBVH()->NodeInfoBuffer().size() * sizeof (BVH_Vec4i));
+ aMemBvhUsed += static_cast<Standard_ShortReal> (
+ aTriangleSet->QuadBVH()->MinPointBuffer().size() * sizeof (BVH_Vec3f));
+ aMemBvhUsed += static_cast<Standard_ShortReal> (
+ aTriangleSet->QuadBVH()->MaxPointBuffer().size() * sizeof (BVH_Vec3f));
}
- aMemUsed += static_cast<Standard_ShortReal> (
- myRaytraceGeometry.BVH()->NodeInfoBuffer().size() * sizeof (BVH_Vec4i));
- aMemUsed += static_cast<Standard_ShortReal> (
- myRaytraceGeometry.BVH()->MinPointBuffer().size() * sizeof (BVH_Vec3f));
- aMemUsed += static_cast<Standard_ShortReal> (
- myRaytraceGeometry.BVH()->MaxPointBuffer().size() * sizeof (BVH_Vec3f));
+ aMemBvhUsed += static_cast<Standard_ShortReal> (
+ myRaytraceGeometry.QuadBVH()->NodeInfoBuffer().size() * sizeof (BVH_Vec4i));
+ aMemBvhUsed += static_cast<Standard_ShortReal> (
+ myRaytraceGeometry.QuadBVH()->MinPointBuffer().size() * sizeof (BVH_Vec3f));
+ aMemBvhUsed += static_cast<Standard_ShortReal> (
+ myRaytraceGeometry.QuadBVH()->MaxPointBuffer().size() * sizeof (BVH_Vec3f));
- std::cout << "GPU Memory Used (MB): ~" << aMemUsed / 1048576 << std::endl;
+ std::cout << "GPU Memory Used (Mb):\n"
+ << "\tFor mesh: " << aMemTrgUsed / 1048576 << "\n"
+ << "\tFor BVHs: " << aMemBvhUsed / 1048576 << "\n";
#endif
}
// =======================================================================
-// function : UpdateRaytraceLightSources
+// function : updateRaytraceLightSources
// purpose : Updates 3D scene light sources for ray-tracing
// =======================================================================
Standard_Boolean OpenGl_View::updateRaytraceLightSources (const OpenGl_Mat4& theInvModelView, const Handle(OpenGl_Context)& theGlContext)
{
- myRaytraceGeometry.Sources.clear();
-
- myRaytraceGeometry.Ambient = BVH_Vec4f (0.0f, 0.0f, 0.0f, 0.0f);
-
- for (OpenGl_ListOfLight::Iterator anItl (LightList()); anItl.More(); anItl.Next())
+ std::vector<Handle(Graphic3d_CLight)> aLightSources;
+ myRaytraceGeometry.Ambient = BVH_Vec4f (0.f, 0.f, 0.f, 0.f);
+ if (myShadingModel != Graphic3d_TOSM_UNLIT
+ && !myLights.IsNull())
{
- const OpenGl_Light& aLight = anItl.Value();
+ const Graphic3d_Vec4& anAmbient = myLights->AmbientColor();
+ myRaytraceGeometry.Ambient = BVH_Vec4f (anAmbient.r(), anAmbient.g(), anAmbient.b(), 0.0f);
- if (aLight.Type == Visual3d_TOLS_AMBIENT)
+ // move positional light sources at the front of the list
+ aLightSources.reserve (myLights->Extent());
+ for (Graphic3d_LightSet::Iterator aLightIter (myLights, Graphic3d_LightSet::IterationFilter_ExcludeDisabledAndAmbient);
+ aLightIter.More(); aLightIter.Next())
{
- myRaytraceGeometry.Ambient += BVH_Vec4f (aLight.Color.r(),
- aLight.Color.g(),
- aLight.Color.b(),
- 0.0f);
- continue;
+ const Graphic3d_CLight& aLight = *aLightIter.Value();
+ if (aLight.Type() != Graphic3d_TOLS_DIRECTIONAL)
+ {
+ aLightSources.push_back (aLightIter.Value());
+ }
+ }
+
+ for (Graphic3d_LightSet::Iterator aLightIter (myLights, Graphic3d_LightSet::IterationFilter_ExcludeDisabledAndAmbient);
+ aLightIter.More(); aLightIter.Next())
+ {
+ if (aLightIter.Value()->Type() == Graphic3d_TOLS_DIRECTIONAL)
+ {
+ aLightSources.push_back (aLightIter.Value());
+ }
}
+ }
+
+ // get number of 'real' (not ambient) light sources
+ const size_t aNbLights = aLightSources.size();
+ Standard_Boolean wasUpdated = myRaytraceGeometry.Sources.size () != aNbLights;
+ if (wasUpdated)
+ {
+ myRaytraceGeometry.Sources.resize (aNbLights);
+ }
- BVH_Vec4f aDiffuse (aLight.Color.r(),
- aLight.Color.g(),
- aLight.Color.b(),
- 1.0f);
+ for (size_t aLightIdx = 0, aRealIdx = 0; aLightIdx < aLightSources.size(); ++aLightIdx)
+ {
+ const Graphic3d_CLight& aLight = *aLightSources[aLightIdx];
+ const Graphic3d_Vec4& aLightColor = aLight.PackedColor();
+ BVH_Vec4f aEmission (aLightColor.r() * aLight.Intensity(),
+ aLightColor.g() * aLight.Intensity(),
+ aLightColor.b() * aLight.Intensity(),
+ 1.0f);
- BVH_Vec4f aPosition (-aLight.Direction.x(),
- -aLight.Direction.y(),
- -aLight.Direction.z(),
+ BVH_Vec4f aPosition (-aLight.PackedDirection().x(),
+ -aLight.PackedDirection().y(),
+ -aLight.PackedDirection().z(),
0.0f);
- if (aLight.Type != Visual3d_TOLS_DIRECTIONAL)
+ if (aLight.Type() != Graphic3d_TOLS_DIRECTIONAL)
{
- aPosition = BVH_Vec4f (aLight.Position.x(),
- aLight.Position.y(),
- aLight.Position.z(),
+ aPosition = BVH_Vec4f (static_cast<float>(aLight.Position().X()),
+ static_cast<float>(aLight.Position().Y()),
+ static_cast<float>(aLight.Position().Z()),
1.0f);
+
+ // store smoothing radius in W-component
+ aEmission.w() = Max (aLight.Smoothness(), 0.f);
+ }
+ else
+ {
+ // store cosine of smoothing angle in W-component
+ aEmission.w() = cosf (Min (Max (aLight.Smoothness(), 0.f), static_cast<Standard_ShortReal> (M_PI / 2.0)));
}
- if (aLight.IsHeadlight)
+ if (aLight.IsHeadlight())
{
aPosition = theInvModelView * aPosition;
}
- myRaytraceGeometry.Sources.push_back (OpenGl_RaytraceLight (aDiffuse, aPosition));
+ for (int aK = 0; aK < 4; ++aK)
+ {
+ wasUpdated |= (aEmission[aK] != myRaytraceGeometry.Sources[aRealIdx].Emission[aK])
+ || (aPosition[aK] != myRaytraceGeometry.Sources[aRealIdx].Position[aK]);
+ }
+
+ if (wasUpdated)
+ {
+ myRaytraceGeometry.Sources[aRealIdx] = OpenGl_RaytraceLight (aEmission, aPosition);
+ }
+
+ ++aRealIdx;
}
- if (myRaytraceLightSrcTexture.IsNull()) // create light source buffer
+ if (myRaytraceLightSrcTexture.IsNull()) // create light source buffer
{
myRaytraceLightSrcTexture = new OpenGl_TextureBufferArb;
-
- if (!myRaytraceLightSrcTexture->Create (theGlContext))
- {
-#ifdef RAY_TRACE_PRINT_INFO
- std::cout << "Error: Failed to create light source buffer" << std::endl;
-#endif
- return Standard_False;
- }
}
-
- if (myRaytraceGeometry.Sources.size() != 0)
+
+ if (myRaytraceGeometry.Sources.size() != 0 && wasUpdated)
{
const GLfloat* aDataPtr = myRaytraceGeometry.Sources.front().Packed();
if (!myRaytraceLightSrcTexture->Init (theGlContext, 4, GLsizei (myRaytraceGeometry.Sources.size() * 2), aDataPtr))
#endif
return Standard_False;
}
+
+ myAccumFrames = 0; // accumulation should be restarted
}
return Standard_True;
}
// =======================================================================
-// function : UpdateRaytraceEnvironmentMap
-// purpose : Updates environment map for ray-tracing
+// function : setUniformState
+// purpose : Sets uniform state for the given ray-tracing shader program
// =======================================================================
-Standard_Boolean OpenGl_View::updateRaytraceEnvironmentMap (const Handle(OpenGl_Context)& theGlContext)
+Standard_Boolean OpenGl_View::setUniformState (const Standard_Integer theProgramId,
+ const Standard_Integer theWinSizeX,
+ const Standard_Integer theWinSizeY,
+ Graphic3d_Camera::Projection theProjection,
+ const Handle(OpenGl_Context)& theGlContext)
{
- Standard_Boolean aResult = Standard_True;
+ // Get projection state
+ OpenGl_MatrixState<Standard_ShortReal>& aCntxProjectionState = theGlContext->ProjectionState;
- if (!myToUpdateEnvironmentMap)
+ OpenGl_Mat4 aViewPrjMat;
+ OpenGl_Mat4 anUnviewMat;
+ OpenGl_Vec3 aOrigins[4];
+ OpenGl_Vec3 aDirects[4];
+
+ if (myCamera->IsOrthographic()
+ || !myRenderParams.IsGlobalIlluminationEnabled)
{
- return aResult;
+ updateCamera (myCamera->OrientationMatrixF(),
+ aCntxProjectionState.Current(),
+ aOrigins,
+ aDirects,
+ aViewPrjMat,
+ anUnviewMat);
}
-
- for (Standard_Integer anIdx = 0; anIdx < 2; ++anIdx)
+ else
{
- const Handle(OpenGl_ShaderProgram)& aProgram =
- anIdx == 0 ? myRaytraceProgram : myPostFSAAProgram;
-
- if (!aProgram.IsNull())
- {
- aResult &= theGlContext->BindProgram (aProgram);
-
- if (!myTextureEnv.IsNull() && mySurfaceDetail != Visual3d_TOD_NONE)
- {
- myTextureEnv->Bind (theGlContext,
- GL_TEXTURE0 + OpenGl_RT_EnvironmentMapTexture);
-
- aResult &= aProgram->SetUniform (theGlContext,
- myUniformLocations[anIdx][OpenGl_RT_uEnvMapEnable], 1);
- }
- else
- {
- aResult &= aProgram->SetUniform (theGlContext,
- myUniformLocations[anIdx][OpenGl_RT_uEnvMapEnable], 0);
- }
- }
+ updatePerspCameraPT (myCamera->OrientationMatrixF(),
+ aCntxProjectionState.Current(),
+ theProjection,
+ aViewPrjMat,
+ anUnviewMat,
+ theWinSizeX,
+ theWinSizeY);
}
- myToUpdateEnvironmentMap = Standard_False;
-
- theGlContext->BindProgram (NULL);
-
- return aResult;
-}
-
-// =======================================================================
-// function : SetUniformState
-// purpose : Sets uniform state for the given ray-tracing shader program
-// =======================================================================
-Standard_Boolean OpenGl_View::setUniformState (const Graphic3d_CView& theCView,
- const OpenGl_Vec3* theOrigins,
- const OpenGl_Vec3* theDirects,
- const OpenGl_Mat4& theUnviewMat,
- const Standard_Integer theProgramId,
- const Handle(OpenGl_Context)& theGlContext)
-{
- Handle(OpenGl_ShaderProgram)& theProgram =
- theProgramId == 0 ? myRaytraceProgram : myPostFSAAProgram;
+ Handle(OpenGl_ShaderProgram)& theProgram = theProgramId == 0
+ ? myRaytraceProgram
+ : myPostFSAAProgram;
if (theProgram.IsNull())
{
return Standard_False;
}
-
- Standard_Boolean aResult = Standard_True;
-
- const Standard_Integer aLightSourceBufferSize =
- static_cast<Standard_Integer> (myRaytraceGeometry.Sources.size());
-
+
+ theProgram->SetUniform(theGlContext, "uEyeOrig", myEyeOrig);
+ theProgram->SetUniform(theGlContext, "uEyeView", myEyeView);
+ theProgram->SetUniform(theGlContext, "uEyeVert", myEyeVert);
+ theProgram->SetUniform(theGlContext, "uEyeSide", myEyeSide);
+ theProgram->SetUniform(theGlContext, "uEyeSize", myEyeSize);
+
+ theProgram->SetUniform(theGlContext, "uApertureRadius", myRenderParams.CameraApertureRadius);
+ theProgram->SetUniform(theGlContext, "uFocalPlaneDist", myRenderParams.CameraFocalPlaneDist);
+
// Set camera state
- aResult &= theProgram->SetUniform (theGlContext,
- myUniformLocations[theProgramId][OpenGl_RT_uOriginLB], theOrigins[0]);
- aResult &= theProgram->SetUniform (theGlContext,
- myUniformLocations[theProgramId][OpenGl_RT_uOriginRB], theOrigins[1]);
- aResult &= theProgram->SetUniform (theGlContext,
- myUniformLocations[theProgramId][OpenGl_RT_uOriginLT], theOrigins[2]);
- aResult &= theProgram->SetUniform (theGlContext,
- myUniformLocations[theProgramId][OpenGl_RT_uOriginRT], theOrigins[3]);
- aResult &= theProgram->SetUniform (theGlContext,
- myUniformLocations[theProgramId][OpenGl_RT_uDirectLB], theDirects[0]);
- aResult &= theProgram->SetUniform (theGlContext,
- myUniformLocations[theProgramId][OpenGl_RT_uDirectRB], theDirects[1]);
- aResult &= theProgram->SetUniform (theGlContext,
- myUniformLocations[theProgramId][OpenGl_RT_uDirectLT], theDirects[2]);
- aResult &= theProgram->SetUniform (theGlContext,
- myUniformLocations[theProgramId][OpenGl_RT_uDirectRT], theDirects[3]);
- aResult &= theProgram->SetUniform (theGlContext,
- myUniformLocations[theProgramId][OpenGl_RT_uUnviewMat], theUnviewMat);
-
- // Set scene parameters
- aResult &= theProgram->SetUniform (theGlContext,
+ theProgram->SetUniform (theGlContext,
+ myUniformLocations[theProgramId][OpenGl_RT_uOriginLB], aOrigins[0]);
+ theProgram->SetUniform (theGlContext,
+ myUniformLocations[theProgramId][OpenGl_RT_uOriginRB], aOrigins[1]);
+ theProgram->SetUniform (theGlContext,
+ myUniformLocations[theProgramId][OpenGl_RT_uOriginLT], aOrigins[2]);
+ theProgram->SetUniform (theGlContext,
+ myUniformLocations[theProgramId][OpenGl_RT_uOriginRT], aOrigins[3]);
+ theProgram->SetUniform (theGlContext,
+ myUniformLocations[theProgramId][OpenGl_RT_uDirectLB], aDirects[0]);
+ theProgram->SetUniform (theGlContext,
+ myUniformLocations[theProgramId][OpenGl_RT_uDirectRB], aDirects[1]);
+ theProgram->SetUniform (theGlContext,
+ myUniformLocations[theProgramId][OpenGl_RT_uDirectLT], aDirects[2]);
+ theProgram->SetUniform (theGlContext,
+ myUniformLocations[theProgramId][OpenGl_RT_uDirectRT], aDirects[3]);
+ theProgram->SetUniform (theGlContext,
+ myUniformLocations[theProgramId][OpenGl_RT_uViewPrMat], aViewPrjMat);
+ theProgram->SetUniform (theGlContext,
+ myUniformLocations[theProgramId][OpenGl_RT_uUnviewMat], anUnviewMat);
+
+ // Set screen dimensions
+ myRaytraceProgram->SetUniform (theGlContext,
+ myUniformLocations[theProgramId][OpenGl_RT_uWinSizeX], theWinSizeX);
+ myRaytraceProgram->SetUniform (theGlContext,
+ myUniformLocations[theProgramId][OpenGl_RT_uWinSizeY], theWinSizeY);
+
+ // Set 3D scene parameters
+ theProgram->SetUniform (theGlContext,
myUniformLocations[theProgramId][OpenGl_RT_uSceneRad], myRaytraceSceneRadius);
- aResult &= theProgram->SetUniform (theGlContext,
+ theProgram->SetUniform (theGlContext,
myUniformLocations[theProgramId][OpenGl_RT_uSceneEps], myRaytraceSceneEpsilon);
- aResult &= theProgram->SetUniform (theGlContext,
- myUniformLocations[theProgramId][OpenGl_RT_uLightCount], aLightSourceBufferSize);
- aResult &= theProgram->SetUniform (theGlContext,
- myUniformLocations[theProgramId][OpenGl_RT_uLightAmbnt], myRaytraceGeometry.Ambient);
- // Set run-time rendering options
- aResult &= theProgram->SetUniform (theGlContext,
- myUniformLocations[theProgramId][OpenGl_RT_uShadEnabled], theCView.RenderParams.IsShadowEnabled ? 1 : 0);
- aResult &= theProgram->SetUniform (theGlContext,
- myUniformLocations[theProgramId][OpenGl_RT_uReflEnabled], theCView.RenderParams.IsReflectionEnabled ? 1 : 0);
+ // Set light source parameters
+ const Standard_Integer aLightSourceBufferSize =
+ static_cast<Standard_Integer> (myRaytraceGeometry.Sources.size());
+
+ theProgram->SetUniform (theGlContext,
+ myUniformLocations[theProgramId][OpenGl_RT_uLightCount], aLightSourceBufferSize);
// Set array of 64-bit texture handles
if (theGlContext->arbTexBindless != NULL && myRaytraceGeometry.HasTextures())
{
- aResult &= theProgram->SetUniform (theGlContext, "uTextureSamplers", static_cast<GLsizei> (
- myRaytraceGeometry.TextureHandles().size()), &myRaytraceGeometry.TextureHandles()[0]);
+ const std::vector<GLuint64>& aTextures = myRaytraceGeometry.TextureHandles();
+
+ theProgram->SetUniform (theGlContext, myUniformLocations[theProgramId][OpenGl_RT_uTexSamplersArray],
+ static_cast<GLsizei> (aTextures.size()), reinterpret_cast<const OpenGl_Vec2u*> (&aTextures.front()));
}
- if (!aResult)
+ // Set background colors (only gradient background supported)
+ if (myBgGradientArray != NULL && myBgGradientArray->IsDefined())
{
-#ifdef RAY_TRACE_PRINT_INFO
- std::cout << "Info: Not all uniforms were detected for program " << theProgramId << std::endl;
-#endif
+ theProgram->SetUniform (theGlContext,
+ myUniformLocations[theProgramId][OpenGl_RT_uBackColorTop], myBgGradientArray->GradientColor (0));
+ theProgram->SetUniform (theGlContext,
+ myUniformLocations[theProgramId][OpenGl_RT_uBackColorBot], myBgGradientArray->GradientColor (1));
}
+ else
+ {
+ const OpenGl_Vec4& aBackColor = myBgColor;
- return aResult;
+ theProgram->SetUniform (theGlContext,
+ myUniformLocations[theProgramId][OpenGl_RT_uBackColorTop], aBackColor);
+ theProgram->SetUniform (theGlContext,
+ myUniformLocations[theProgramId][OpenGl_RT_uBackColorBot], aBackColor);
+ }
+
+ // Set environment map parameters
+ const Standard_Boolean toDisableEnvironmentMap = myTextureEnv.IsNull()
+ || myTextureEnv->IsEmpty()
+ || !myTextureEnv->First()->IsValid();
+
+ theProgram->SetUniform (theGlContext,
+ myUniformLocations[theProgramId][OpenGl_RT_uSphereMapEnabled], toDisableEnvironmentMap ? 0 : 1);
+
+ theProgram->SetUniform (theGlContext,
+ myUniformLocations[theProgramId][OpenGl_RT_uSphereMapForBack], myRenderParams.UseEnvironmentMapBackground ? 1 : 0);
+
+ if (myRenderParams.IsGlobalIlluminationEnabled) // GI parameters
+ {
+ theProgram->SetUniform (theGlContext,
+ myUniformLocations[theProgramId][OpenGl_RT_uMaxRadiance], myRenderParams.RadianceClampingValue);
+
+ theProgram->SetUniform (theGlContext,
+ myUniformLocations[theProgramId][OpenGl_RT_uBlockedRngEnabled], myRenderParams.CoherentPathTracingMode ? 1 : 0);
+
+ // Check whether we should restart accumulation for run-time parameters
+ if (myRenderParams.RadianceClampingValue != myRaytraceParameters.RadianceClampingValue
+ || myRenderParams.UseEnvironmentMapBackground != myRaytraceParameters.UseEnvMapForBackground)
+ {
+ myAccumFrames = 0; // accumulation should be restarted
+
+ myRaytraceParameters.RadianceClampingValue = myRenderParams.RadianceClampingValue;
+ myRaytraceParameters.UseEnvMapForBackground = myRenderParams.UseEnvironmentMapBackground;
+ }
+ }
+ else // RT parameters
+ {
+ // Set ambient light source
+ theProgram->SetUniform (theGlContext,
+ myUniformLocations[theProgramId][OpenGl_RT_uLightAmbnt], myRaytraceGeometry.Ambient);
+
+ // Enable/disable run-time ray-tracing effects
+ theProgram->SetUniform (theGlContext,
+ myUniformLocations[theProgramId][OpenGl_RT_uShadowsEnabled], myRenderParams.IsShadowEnabled ? 1 : 0);
+ theProgram->SetUniform (theGlContext,
+ myUniformLocations[theProgramId][OpenGl_RT_uReflectEnabled], myRenderParams.IsReflectionEnabled ? 1 : 0);
+ }
+
+ return Standard_True;
}
// =======================================================================
-// function : BindRaytraceTextures
+// function : bindRaytraceTextures
// purpose : Binds ray-trace textures to corresponding texture units
// =======================================================================
-void OpenGl_View::bindRaytraceTextures (const Handle(OpenGl_Context)& theGlContext)
+void OpenGl_View::bindRaytraceTextures (const Handle(OpenGl_Context)& theGlContext,
+ int theStereoView)
{
- mySceneMinPointTexture->BindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_SceneMinPointTexture);
- mySceneMaxPointTexture->BindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_SceneMaxPointTexture);
- mySceneNodeInfoTexture->BindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_SceneNodeInfoTexture);
- myGeometryVertexTexture->BindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryVertexTexture);
- myGeometryNormalTexture->BindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryNormalTexture);
- myGeometryTexCrdTexture->BindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryTexCrdTexture);
- myGeometryTriangTexture->BindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryTriangTexture);
- mySceneTransformTexture->BindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_SceneTransformTexture);
- myRaytraceMaterialTexture->BindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_RaytraceMaterialTexture);
- myRaytraceLightSrcTexture->BindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_RaytraceLightSrcTexture);
-
- if (!myOpenGlFBO.IsNull())
- {
- myOpenGlFBO->ColorTexture()->Bind (theGlContext, GL_TEXTURE0 + OpenGl_RT_OpenGlColorTexture);
- myOpenGlFBO->DepthStencilTexture()->Bind (theGlContext, GL_TEXTURE0 + OpenGl_RT_OpenGlDepthTexture);
+ if (myRaytraceParameters.AdaptiveScreenSampling
+ && myRaytraceParameters.GlobalIllumination)
+ {
+ #if !defined(GL_ES_VERSION_2_0)
+ theGlContext->core42->glBindImageTexture (OpenGl_RT_OutputImage,
+ myRaytraceOutputTexture[theStereoView]->TextureId(), 0, GL_TRUE, 0, GL_READ_WRITE, GL_R32F);
+ theGlContext->core42->glBindImageTexture (OpenGl_RT_VisualErrorImage,
+ myRaytraceVisualErrorTexture[theStereoView]->TextureId(), 0, GL_TRUE, 0, GL_READ_WRITE, GL_R32I);
+ theGlContext->core42->glBindImageTexture (OpenGl_RT_TileOffsetsImage,
+ myRaytraceTileOffsetsTexture[theStereoView]->TextureId(), 0, GL_TRUE, 0, GL_READ_ONLY, GL_RG32I);
+ #else
+ (void )theStereoView;
+ #endif
}
+
+ if (!myTextureEnv.IsNull()
+ && !myTextureEnv->IsEmpty()
+ && myTextureEnv->First()->IsValid())
+ {
+ myTextureEnv->First()->Bind (theGlContext, OpenGl_RT_EnvironmentMapTexture);
+ }
+
+ mySceneMinPointTexture ->BindTexture (theGlContext, OpenGl_RT_SceneMinPointTexture);
+ mySceneMaxPointTexture ->BindTexture (theGlContext, OpenGl_RT_SceneMaxPointTexture);
+ mySceneNodeInfoTexture ->BindTexture (theGlContext, OpenGl_RT_SceneNodeInfoTexture);
+ myGeometryVertexTexture ->BindTexture (theGlContext, OpenGl_RT_GeometryVertexTexture);
+ myGeometryNormalTexture ->BindTexture (theGlContext, OpenGl_RT_GeometryNormalTexture);
+ myGeometryTexCrdTexture ->BindTexture (theGlContext, OpenGl_RT_GeometryTexCrdTexture);
+ myGeometryTriangTexture ->BindTexture (theGlContext, OpenGl_RT_GeometryTriangTexture);
+ mySceneTransformTexture ->BindTexture (theGlContext, OpenGl_RT_SceneTransformTexture);
+ myRaytraceMaterialTexture->BindTexture (theGlContext, OpenGl_RT_RaytraceMaterialTexture);
+ myRaytraceLightSrcTexture->BindTexture (theGlContext, OpenGl_RT_RaytraceLightSrcTexture);
}
// =======================================================================
-// function : UnbindRaytraceTextures
+// function : unbindRaytraceTextures
// purpose : Unbinds ray-trace textures from corresponding texture units
// =======================================================================
void OpenGl_View::unbindRaytraceTextures (const Handle(OpenGl_Context)& theGlContext)
{
- mySceneMinPointTexture->UnbindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_SceneMinPointTexture);
- mySceneMaxPointTexture->UnbindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_SceneMaxPointTexture);
- mySceneNodeInfoTexture->UnbindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_SceneNodeInfoTexture);
- myGeometryVertexTexture->UnbindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryVertexTexture);
- myGeometryNormalTexture->UnbindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryNormalTexture);
- myGeometryTexCrdTexture->UnbindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryTexCrdTexture);
- myGeometryTriangTexture->UnbindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryTriangTexture);
- mySceneTransformTexture->UnbindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_SceneTransformTexture);
- myRaytraceMaterialTexture->UnbindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_RaytraceMaterialTexture);
- myRaytraceLightSrcTexture->UnbindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_RaytraceLightSrcTexture);
-
- if (!myOpenGlFBO.IsNull())
- {
- myOpenGlFBO->ColorTexture()->Unbind (theGlContext, GL_TEXTURE0 + OpenGl_RT_OpenGlColorTexture);
- myOpenGlFBO->DepthStencilTexture()->Unbind (theGlContext, GL_TEXTURE0 + OpenGl_RT_OpenGlDepthTexture);
- }
+ mySceneMinPointTexture ->UnbindTexture (theGlContext, OpenGl_RT_SceneMinPointTexture);
+ mySceneMaxPointTexture ->UnbindTexture (theGlContext, OpenGl_RT_SceneMaxPointTexture);
+ mySceneNodeInfoTexture ->UnbindTexture (theGlContext, OpenGl_RT_SceneNodeInfoTexture);
+ myGeometryVertexTexture ->UnbindTexture (theGlContext, OpenGl_RT_GeometryVertexTexture);
+ myGeometryNormalTexture ->UnbindTexture (theGlContext, OpenGl_RT_GeometryNormalTexture);
+ myGeometryTexCrdTexture ->UnbindTexture (theGlContext, OpenGl_RT_GeometryTexCrdTexture);
+ myGeometryTriangTexture ->UnbindTexture (theGlContext, OpenGl_RT_GeometryTriangTexture);
+ mySceneTransformTexture ->UnbindTexture (theGlContext, OpenGl_RT_SceneTransformTexture);
+ myRaytraceMaterialTexture->UnbindTexture (theGlContext, OpenGl_RT_RaytraceMaterialTexture);
+ myRaytraceLightSrcTexture->UnbindTexture (theGlContext, OpenGl_RT_RaytraceLightSrcTexture);
theGlContext->core15fwd->glActiveTexture (GL_TEXTURE0);
}
// =======================================================================
-// function : RunRaytraceShaders
+// function : runRaytraceShaders
// purpose : Runs ray-tracing shader programs
// =======================================================================
-Standard_Boolean OpenGl_View::runRaytraceShaders (const Graphic3d_CView& theCView,
- const Standard_Integer theSizeX,
+Standard_Boolean OpenGl_View::runRaytraceShaders (const Standard_Integer theSizeX,
const Standard_Integer theSizeY,
- const OpenGl_Vec3* theOrigins,
- const OpenGl_Vec3* theDirects,
- const OpenGl_Mat4& theUnviewMat,
- OpenGl_FrameBuffer* theOutputFBO,
+ Graphic3d_Camera::Projection theProjection,
+ OpenGl_FrameBuffer* theReadDrawFbo,
const Handle(OpenGl_Context)& theGlContext)
{
- bindRaytraceTextures (theGlContext);
-
- if (theCView.RenderParams.IsAntialiasingEnabled) // render source image to FBO
- {
- myRaytraceFBO1->BindBuffer (theGlContext);
-
- glDisable (GL_BLEND);
- }
-
Standard_Boolean aResult = theGlContext->BindProgram (myRaytraceProgram);
- aResult &= setUniformState (theCView,
- theOrigins,
- theDirects,
- theUnviewMat,
- 0, // ID of RT program
+ aResult &= setUniformState (0,
+ theSizeX,
+ theSizeY,
+ theProjection,
theGlContext);
- myRaytraceScreenQuad.BindVertexAttrib (theGlContext, Graphic3d_TOA_POS);
+ if (myRaytraceParameters.GlobalIllumination) // path tracing
{
- if (aResult)
- theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
+ aResult &= runPathtrace (theSizeX, theSizeY, theProjection, theGlContext);
+ aResult &= runPathtraceOut (theProjection, theReadDrawFbo, theGlContext);
}
- myRaytraceScreenQuad.UnbindVertexAttrib (theGlContext, Graphic3d_TOA_POS);
-
- if (!theCView.RenderParams.IsAntialiasingEnabled || !aResult)
+ else // Whitted-style ray-tracing
{
- unbindRaytraceTextures (theGlContext);
+ aResult &= runRaytrace (theSizeX, theSizeY, theProjection, theReadDrawFbo, theGlContext);
+ }
- theGlContext->BindProgram (NULL);
+ return aResult;
+}
- return aResult;
- }
+// =======================================================================
+// function : runRaytrace
+// purpose : Runs Whitted-style ray-tracing
+// =======================================================================
+Standard_Boolean OpenGl_View::runRaytrace (const Standard_Integer theSizeX,
+ const Standard_Integer theSizeY,
+ Graphic3d_Camera::Projection theProjection,
+ OpenGl_FrameBuffer* theReadDrawFbo,
+ const Handle(OpenGl_Context)& theGlContext)
+{
+ Standard_Boolean aResult = Standard_True;
- myRaytraceFBO1->ColorTexture()->Bind (theGlContext, GL_TEXTURE0 + OpenGl_RT_FSAAInputTexture);
+ // Choose proper set of frame buffers for stereo rendering
+ const Standard_Integer aFBOIdx = (theProjection == Graphic3d_Camera::Projection_MonoRightEye) ? 1 : 0;
+ bindRaytraceTextures (theGlContext, aFBOIdx);
- aResult &= theGlContext->BindProgram (myPostFSAAProgram);
+ if (myRenderParams.IsAntialiasingEnabled) // if second FSAA pass is used
+ {
+ myRaytraceFBO1[aFBOIdx]->BindBuffer (theGlContext);
- aResult &= setUniformState (theCView,
- theOrigins,
- theDirects,
- theUnviewMat,
- 1, // ID of FSAA program
- theGlContext);
+ glClear (GL_DEPTH_BUFFER_BIT); // render the image with depth
+ }
- myRaytraceScreenQuad.BindVertexAttrib (theGlContext, Graphic3d_TOA_POS);
+ theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
+
+ if (myRenderParams.IsAntialiasingEnabled)
{
+ glDisable (GL_DEPTH_TEST); // improve jagged edges without depth buffer
+
+ // bind ray-tracing output image as input
+ myRaytraceFBO1[aFBOIdx]->ColorTexture()->Bind (theGlContext, OpenGl_RT_FsaaInputTexture);
+
+ aResult &= theGlContext->BindProgram (myPostFSAAProgram);
+
+ aResult &= setUniformState (1 /* FSAA ID */,
+ theSizeX,
+ theSizeY,
+ theProjection,
+ theGlContext);
+
// Perform multi-pass adaptive FSAA using ping-pong technique.
// We use 'FLIPTRI' sampling pattern changing for every pixel
// (3 additional samples per pixel, the 1st sample is already
aResult &= myPostFSAAProgram->SetUniform (theGlContext,
myUniformLocations[1][OpenGl_RT_uOffsetY], aOffsetY);
- Handle(OpenGl_FrameBuffer)& aFramebuffer = anIt % 2 ? myRaytraceFBO2 : myRaytraceFBO1;
+ Handle(OpenGl_FrameBuffer)& aFramebuffer = anIt % 2
+ ? myRaytraceFBO2[aFBOIdx]
+ : myRaytraceFBO1[aFBOIdx];
- if (anIt == 3) // disable FBO on last iteration
- {
- glEnable (GL_BLEND);
-
- if (theOutputFBO != NULL)
- theOutputFBO->BindBuffer (theGlContext);
- }
- else
- {
- aFramebuffer->BindBuffer (theGlContext);
- }
+ aFramebuffer->BindBuffer (theGlContext);
+ // perform adaptive FSAA pass
theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
- if (anIt != 3) // set input for the next pass
- {
- aFramebuffer->ColorTexture()->Bind (theGlContext, GL_TEXTURE0 + OpenGl_RT_FSAAInputTexture);
- }
+ aFramebuffer->ColorTexture()->Bind (theGlContext, OpenGl_RT_FsaaInputTexture);
+ }
+
+ const Handle(OpenGl_FrameBuffer)& aRenderImageFramebuffer = myRaytraceFBO2[aFBOIdx];
+ const Handle(OpenGl_FrameBuffer)& aDepthSourceFramebuffer = myRaytraceFBO1[aFBOIdx];
+
+ glEnable (GL_DEPTH_TEST);
+
+ // Display filtered image
+ theGlContext->BindProgram (myOutImageProgram);
+
+ if (theReadDrawFbo != NULL)
+ {
+ theReadDrawFbo->BindBuffer (theGlContext);
+ }
+ else
+ {
+ aRenderImageFramebuffer->UnbindBuffer (theGlContext);
}
+
+ aRenderImageFramebuffer->ColorTexture() ->Bind (theGlContext, OpenGl_RT_PrevAccumTexture);
+ aDepthSourceFramebuffer->DepthStencilTexture()->Bind (theGlContext, OpenGl_RT_RaytraceDepthTexture);
+
+ // copy the output image with depth values
+ theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
+
+ aDepthSourceFramebuffer->DepthStencilTexture()->Unbind (theGlContext, OpenGl_RT_RaytraceDepthTexture);
+ aRenderImageFramebuffer->ColorTexture() ->Unbind (theGlContext, OpenGl_RT_PrevAccumTexture);
}
- myRaytraceScreenQuad.UnbindVertexAttrib (theGlContext, Graphic3d_TOA_POS);
unbindRaytraceTextures (theGlContext);
}
// =======================================================================
-// function : Raytrace
-// purpose : Redraws the window using OpenGL/GLSL ray-tracing
+// function : runPathtrace
+// purpose : Runs path tracing shader
// =======================================================================
-Standard_Boolean OpenGl_View::raytrace (const Graphic3d_CView& theCView,
- const Standard_Integer theSizeX,
- const Standard_Integer theSizeY,
- OpenGl_FrameBuffer* theOutputFBO,
- const Handle(OpenGl_Context)& theGlContext)
+Standard_Boolean OpenGl_View::runPathtrace (const Standard_Integer theSizeX,
+ const Standard_Integer theSizeY,
+ const Graphic3d_Camera::Projection theProjection,
+ const Handle(OpenGl_Context)& theGlContext)
{
- if (!initRaytraceResources (theCView, theGlContext))
+ if (myToUpdateEnvironmentMap) // check whether the map was changed
{
- return Standard_False;
+ myAccumFrames = myToUpdateEnvironmentMap = 0;
+ }
+
+ if (myRenderParams.CameraApertureRadius != myPrevCameraApertureRadius
+ || myRenderParams.CameraFocalPlaneDist != myPrevCameraFocalPlaneDist)
+ {
+ myPrevCameraApertureRadius = myRenderParams.CameraApertureRadius;
+ myPrevCameraFocalPlaneDist = myRenderParams.CameraFocalPlaneDist;
+ myAccumFrames = 0;
}
- if (!resizeRaytraceBuffers (theSizeX, theSizeY, theGlContext))
+ // Choose proper set of frame buffers for stereo rendering
+ const Standard_Integer aFBOIdx = (theProjection == Graphic3d_Camera::Projection_MonoRightEye) ? 1 : 0;
+
+ if (myRaytraceParameters.AdaptiveScreenSampling)
{
- return Standard_False;
+ if (myAccumFrames == 0)
+ {
+ myTileSampler.Reset(); // reset tile sampler to its initial state
+
+ // Adaptive sampling is starting at the second frame
+ myTileSampler.UploadOffsets (theGlContext, myRaytraceTileOffsetsTexture[aFBOIdx], false);
+
+ #if !defined(GL_ES_VERSION_2_0)
+ theGlContext->core44->glClearTexImage (myRaytraceOutputTexture[aFBOIdx]->TextureId(), 0, GL_RED, GL_FLOAT, NULL);
+ #endif
+ }
+
+ // Clear adaptive screen sampling images
+ #if !defined(GL_ES_VERSION_2_0)
+ theGlContext->core44->glClearTexImage (myRaytraceVisualErrorTexture[aFBOIdx]->TextureId(), 0, GL_RED_INTEGER, GL_INT, NULL);
+ #endif
}
- if (!updateRaytraceEnvironmentMap (theGlContext))
+ bindRaytraceTextures (theGlContext, aFBOIdx);
+
+ const Handle(OpenGl_FrameBuffer)& anAccumImageFramebuffer = myAccumFrames % 2 ? myRaytraceFBO2[aFBOIdx] : myRaytraceFBO1[aFBOIdx];
+ anAccumImageFramebuffer->ColorTexture()->Bind (theGlContext, OpenGl_RT_PrevAccumTexture);
+
+ // Set frame accumulation weight
+ myRaytraceProgram->SetUniform (theGlContext, myUniformLocations[0][OpenGl_RT_uAccumSamples], myAccumFrames);
+
+ // Set random number generator seed
+ if (myAccumFrames == 0)
{
- return Standard_False;
+ myRNG.SetSeed(); // start RNG from beginning
+ }
+ myRaytraceProgram->SetUniform (theGlContext, myUniformLocations[0][OpenGl_RT_uFrameRndSeed], static_cast<Standard_Integer> (myRNG.NextInt() >> 2));
+
+ // Set image uniforms for render program
+ if (myRaytraceParameters.AdaptiveScreenSampling)
+ {
+ myRaytraceProgram->SetUniform (theGlContext, myUniformLocations[0][OpenGl_RT_uRenderImage], OpenGl_RT_OutputImage);
+ myRaytraceProgram->SetUniform (theGlContext, myUniformLocations[0][OpenGl_RT_uOffsetImage], OpenGl_RT_TileOffsetsImage);
+ myRaytraceProgram->SetUniform (theGlContext, myUniformLocations[0][OpenGl_RT_uTileSize], myTileSampler.TileSize());
+ }
+
+ const Handle(OpenGl_FrameBuffer)& aRenderImageFramebuffer = myAccumFrames % 2 ? myRaytraceFBO1[aFBOIdx] : myRaytraceFBO2[aFBOIdx];
+ aRenderImageFramebuffer->BindBuffer (theGlContext);
+ if (myRaytraceParameters.AdaptiveScreenSampling)
+ {
+ // extend viewport here, so that tiles at boundaries (cut tile size by target rendering viewport)
+ // redirected to inner tiles (full tile size) are drawn entirely
+ const Graphic3d_Vec2i anOffsetViewport = myTileSampler.OffsetTilesViewport (myAccumFrames > 1); // shrunk offsets texture will be uploaded since 3rd frame
+ glViewport (0, 0, anOffsetViewport.x(), anOffsetViewport.y());
+ }
+
+ // Generate for the given RNG seed
+ glDisable (GL_DEPTH_TEST);
+ theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
+
+ aRenderImageFramebuffer->UnbindBuffer (theGlContext);
+
+ if (myRaytraceParameters.AdaptiveScreenSampling)
+ {
+ glViewport (0, 0, theSizeX, theSizeY);
+ }
+ return true;
+}
+
+// =======================================================================
+// function : runPathtraceOut
+// purpose :
+// =======================================================================
+Standard_Boolean OpenGl_View::runPathtraceOut (const Graphic3d_Camera::Projection theProjection,
+ OpenGl_FrameBuffer* theReadDrawFbo,
+ const Handle(OpenGl_Context)& theGlContext)
+{
+ // Output accumulated path traced image
+ theGlContext->BindProgram (myOutImageProgram);
+
+ // Choose proper set of frame buffers for stereo rendering
+ const Standard_Integer aFBOIdx = (theProjection == Graphic3d_Camera::Projection_MonoRightEye) ? 1 : 0;
+
+ if (myRaytraceParameters.AdaptiveScreenSampling)
+ {
+ // Set uniforms for display program
+ myOutImageProgram->SetUniform (theGlContext, "uRenderImage", OpenGl_RT_OutputImage);
+ myOutImageProgram->SetUniform (theGlContext, "uAccumFrames", myAccumFrames);
+ myOutImageProgram->SetUniform (theGlContext, "uVarianceImage", OpenGl_RT_VisualErrorImage);
+ myOutImageProgram->SetUniform (theGlContext, "uDebugAdaptive", myRenderParams.ShowSamplingTiles ? 1 : 0);
+ myOutImageProgram->SetUniform (theGlContext, "uTileSize", myTileSampler.TileSize());
+ myOutImageProgram->SetUniform (theGlContext, "uVarianceScaleFactor", myTileSampler.VarianceScaleFactor());
}
- // Get model-view and projection matrices
- OpenGl_Mat4 aOrientationMatrix;
- OpenGl_Mat4 aViewMappingMatrix;
- OpenGl_Mat4 aInverOrientMatrix;
+ if (myRaytraceParameters.GlobalIllumination)
+ {
+ myOutImageProgram->SetUniform(theGlContext, "uExposure", myRenderParams.Exposure);
+ switch (myRaytraceParameters.ToneMappingMethod)
+ {
+ case Graphic3d_ToneMappingMethod_Disabled:
+ break;
+ case Graphic3d_ToneMappingMethod_Filmic:
+ myOutImageProgram->SetUniform (theGlContext, "uWhitePoint", myRenderParams.WhitePoint);
+ break;
+ }
+ }
+
+ if (theReadDrawFbo != NULL)
+ {
+ theReadDrawFbo->BindBuffer (theGlContext);
+ }
+
+ const Handle(OpenGl_FrameBuffer)& aRenderImageFramebuffer = myAccumFrames % 2 ? myRaytraceFBO1[aFBOIdx] : myRaytraceFBO2[aFBOIdx];
+ aRenderImageFramebuffer->ColorTexture()->Bind (theGlContext, OpenGl_RT_PrevAccumTexture);
- GetMatrices (aOrientationMatrix,
- aViewMappingMatrix);
+ // Copy accumulated image with correct depth values
+ glEnable (GL_DEPTH_TEST);
+ theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
- aOrientationMatrix.Inverted (aInverOrientMatrix);
+ aRenderImageFramebuffer->ColorTexture()->Unbind (theGlContext, OpenGl_RT_PrevAccumTexture);
- if (!updateRaytraceLightSources (aInverOrientMatrix, theGlContext))
+ if (myRaytraceParameters.AdaptiveScreenSampling)
+ {
+ // Download visual error map from the GPU and build adjusted tile offsets for optimal image sampling
+ myTileSampler.GrabVarianceMap (theGlContext, myRaytraceVisualErrorTexture[aFBOIdx]);
+ myTileSampler.UploadOffsets (theGlContext, myRaytraceTileOffsetsTexture[aFBOIdx], myAccumFrames != 0);
+ }
+
+ unbindRaytraceTextures (theGlContext);
+ theGlContext->BindProgram (NULL);
+ return true;
+}
+
+// =======================================================================
+// function : raytrace
+// purpose : Redraws the window using OpenGL/GLSL ray-tracing
+// =======================================================================
+Standard_Boolean OpenGl_View::raytrace (const Standard_Integer theSizeX,
+ const Standard_Integer theSizeY,
+ Graphic3d_Camera::Projection theProjection,
+ OpenGl_FrameBuffer* theReadDrawFbo,
+ const Handle(OpenGl_Context)& theGlContext)
+{
+ if (!initRaytraceResources (theSizeX, theSizeY, theGlContext))
{
return Standard_False;
}
- OpenGl_Vec3 aOrigins[4];
- OpenGl_Vec3 aDirects[4];
- OpenGl_Mat4 anUnviewMat;
+ if (!updateRaytraceBuffers (theSizeX, theSizeY, theGlContext))
+ {
+ return Standard_False;
+ }
- updateCamera (aOrientationMatrix,
- aViewMappingMatrix,
- aOrigins,
- aDirects,
- anUnviewMat);
+ OpenGl_Mat4 aLightSourceMatrix;
- glEnable (GL_BLEND);
- glDisable (GL_DEPTH_TEST);
- glBlendFunc (GL_ONE, GL_SRC_ALPHA);
+ // Get inversed model-view matrix for transforming lights
+ myCamera->OrientationMatrixF().Inverted (aLightSourceMatrix);
- if (theOutputFBO != NULL)
+ if (!updateRaytraceLightSources (aLightSourceMatrix, theGlContext))
{
- theOutputFBO->BindBuffer (theGlContext);
+ return Standard_False;
}
- // Generate ray-traced image
+ // Generate image using Whitted-style ray-tracing or path tracing
if (myIsRaytraceDataValid)
{
- myRaytraceScreenQuad.Bind (theGlContext);
+ myRaytraceScreenQuad.BindVertexAttrib (theGlContext, Graphic3d_TOA_POS);
if (!myRaytraceGeometry.AcquireTextures (theGlContext))
{
- theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB, GL_DEBUG_TYPE_ERROR_ARB,
- 0, GL_DEBUG_SEVERITY_MEDIUM_ARB, "Error: Failed to acquire OpenGL image textures");
+ theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR,
+ 0, GL_DEBUG_SEVERITY_MEDIUM, "Error: Failed to acquire OpenGL image textures");
}
- Standard_Boolean aResult = runRaytraceShaders (theCView,
- theSizeX,
- theSizeY,
- aOrigins,
- aDirects,
- anUnviewMat,
- theOutputFBO,
- theGlContext);
+ glDisable (GL_BLEND);
+
+ const Standard_Boolean aResult = runRaytraceShaders (theSizeX,
+ theSizeY,
+ theProjection,
+ theReadDrawFbo,
+ theGlContext);
if (!aResult)
{
- theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB, GL_DEBUG_TYPE_ERROR_ARB,
- 0, GL_DEBUG_SEVERITY_MEDIUM_ARB, "Error: Failed to execute ray-tracing shaders");
+ theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR,
+ 0, GL_DEBUG_SEVERITY_MEDIUM, "Error: Failed to execute ray-tracing shaders");
}
if (!myRaytraceGeometry.ReleaseTextures (theGlContext))
{
- theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB, GL_DEBUG_TYPE_ERROR_ARB,
- 0, GL_DEBUG_SEVERITY_MEDIUM_ARB, "Error: Failed to release OpenGL image textures");
+ theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR,
+ 0, GL_DEBUG_SEVERITY_MEDIUM, "Error: Failed to release OpenGL image textures");
}
- myRaytraceScreenQuad.Unbind (theGlContext);
+ myRaytraceScreenQuad.UnbindVertexAttrib (theGlContext, Graphic3d_TOA_POS);
}
- glDisable (GL_BLEND);
- glEnable (GL_DEPTH_TEST);
-
return Standard_True;
-}
\ No newline at end of file
+}