1 // Created on: 2015-02-20
2 // Created by: Denis BOGOLEPOV
3 // Copyright (c) 2015 OPEN CASCADE SAS
5 // This file is part of Open CASCADE Technology software library.
7 // This library is free software; you can redistribute it and/or modify it under
8 // the terms of the GNU Lesser General Public License version 2.1 as published
9 // by the Free Software Foundation, with special exception defined in the file
10 // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
11 // distribution for complete text of the license and disclaimer of any warranty.
13 // Alternatively, this file may be used under the terms of Open CASCADE
14 // commercial license or contractual agreement.
16 #include <OpenGl_View.hxx>
18 #include <Graphic3d_TextureParams.hxx>
19 #include <OpenGl_PrimitiveArray.hxx>
20 #include <OpenGl_VertexBuffer.hxx>
21 #include <OpenGl_GlCore44.hxx>
22 #include <OSD_Protection.hxx>
23 #include <OSD_File.hxx>
25 #include "../Shaders/Shaders_RaytraceBase_vs.pxx"
26 #include "../Shaders/Shaders_RaytraceBase_fs.pxx"
27 #include "../Shaders/Shaders_PathtraceBase_fs.pxx"
28 #include "../Shaders/Shaders_RaytraceRender_fs.pxx"
29 #include "../Shaders/Shaders_RaytraceSmooth_fs.pxx"
30 #include "../Shaders/Shaders_Display_fs.pxx"
32 //! Use this macro to output ray-tracing debug info
33 // #define RAY_TRACE_PRINT_INFO
35 #ifdef RAY_TRACE_PRINT_INFO
36 #include <OSD_Timer.hxx>
41 static const OpenGl_Vec4 THE_WHITE_COLOR (1.0f, 1.0f, 1.0f, 1.0f);
42 static const OpenGl_Vec4 THE_BLACK_COLOR (0.0f, 0.0f, 0.0f, 1.0f);
47 //! Defines OpenGL texture samplers.
48 static const Graphic3d_TextureUnit OpenGl_RT_EnvironmentMapTexture = Graphic3d_TextureUnit_0;
50 static const Graphic3d_TextureUnit OpenGl_RT_SceneNodeInfoTexture = Graphic3d_TextureUnit_1;
51 static const Graphic3d_TextureUnit OpenGl_RT_SceneMinPointTexture = Graphic3d_TextureUnit_2;
52 static const Graphic3d_TextureUnit OpenGl_RT_SceneMaxPointTexture = Graphic3d_TextureUnit_3;
53 static const Graphic3d_TextureUnit OpenGl_RT_SceneTransformTexture = Graphic3d_TextureUnit_4;
55 static const Graphic3d_TextureUnit OpenGl_RT_GeometryVertexTexture = Graphic3d_TextureUnit_5;
56 static const Graphic3d_TextureUnit OpenGl_RT_GeometryNormalTexture = Graphic3d_TextureUnit_6;
57 static const Graphic3d_TextureUnit OpenGl_RT_GeometryTexCrdTexture = Graphic3d_TextureUnit_7;
58 static const Graphic3d_TextureUnit OpenGl_RT_GeometryTriangTexture = Graphic3d_TextureUnit_8;
60 static const Graphic3d_TextureUnit OpenGl_RT_RaytraceMaterialTexture = Graphic3d_TextureUnit_9;
61 static const Graphic3d_TextureUnit OpenGl_RT_RaytraceLightSrcTexture = Graphic3d_TextureUnit_10;
63 static const Graphic3d_TextureUnit OpenGl_RT_FsaaInputTexture = Graphic3d_TextureUnit_11;
64 static const Graphic3d_TextureUnit OpenGl_RT_PrevAccumTexture = Graphic3d_TextureUnit_12;
66 static const Graphic3d_TextureUnit OpenGl_RT_RaytraceDepthTexture = Graphic3d_TextureUnit_13;
69 // =======================================================================
70 // function : updateRaytraceGeometry
71 // purpose : Updates 3D scene geometry for ray-tracing
72 // =======================================================================
73 Standard_Boolean OpenGl_View::updateRaytraceGeometry (const RaytraceUpdateMode theMode,
74 const Standard_Integer theViewId,
75 const Handle(OpenGl_Context)& theGlContext)
77 // In 'check' mode (OpenGl_GUM_CHECK) the scene geometry is analyzed for
78 // modifications. This is light-weight procedure performed on each frame
79 if (theMode == OpenGl_GUM_CHECK)
81 if (myRaytraceLayerListState != myZLayers.ModificationStateOfRaytracable())
83 return updateRaytraceGeometry (OpenGl_GUM_PREPARE, theViewId, theGlContext);
86 else if (theMode == OpenGl_GUM_PREPARE)
88 myRaytraceGeometry.ClearMaterials();
90 myArrayToTrianglesMap.clear();
92 myIsRaytraceDataValid = Standard_False;
95 // The set of processed structures (reflected to ray-tracing)
96 // This set is used to remove out-of-date records from the
97 // hash map of structures
98 std::set<const OpenGl_Structure*> anElements;
100 // Set to store all currently visible OpenGL primitive arrays
101 // applicable for ray-tracing
102 std::set<Standard_Size> anArrayIDs;
104 // Set to store all non-raytracable elements allowing tracking
105 // of changes in OpenGL scene (only for path tracing)
106 std::set<Standard_Integer> aNonRaytraceIDs;
108 for (NCollection_List<Handle(Graphic3d_Layer)>::Iterator aLayerIter (myZLayers.Layers()); aLayerIter.More(); aLayerIter.Next())
110 const Handle(OpenGl_Layer)& aLayer = aLayerIter.Value();
111 if (aLayer->NbStructures() == 0
112 || !aLayer->LayerSettings().IsRaytracable()
113 || aLayer->LayerSettings().IsImmediate())
118 const Graphic3d_ArrayOfIndexedMapOfStructure& aStructArray = aLayer->ArrayOfStructures();
119 for (Standard_Integer anIndex = 0; anIndex < aStructArray.Length(); ++anIndex)
121 for (OpenGl_Structure::StructIterator aStructIt (aStructArray.Value (anIndex)); aStructIt.More(); aStructIt.Next())
123 const OpenGl_Structure* aStructure = aStructIt.Value();
125 if (theMode == OpenGl_GUM_CHECK)
127 if (toUpdateStructure (aStructure))
129 return updateRaytraceGeometry (OpenGl_GUM_PREPARE, theViewId, theGlContext);
131 else if (aStructure->IsVisible() && myRaytraceParameters.GlobalIllumination)
133 aNonRaytraceIDs.insert (aStructure->highlight ? aStructure->Id : -aStructure->Id);
136 else if (theMode == OpenGl_GUM_PREPARE)
138 if (!aStructure->IsRaytracable() || !aStructure->IsVisible())
142 else if (!aStructure->ViewAffinity.IsNull() && !aStructure->ViewAffinity->IsVisible (theViewId))
147 for (OpenGl_Structure::GroupIterator aGroupIter (aStructure->Groups()); aGroupIter.More(); aGroupIter.Next())
149 // Extract OpenGL elements from the group (primitives arrays)
150 for (const OpenGl_ElementNode* aNode = aGroupIter.Value()->FirstNode(); aNode != NULL; aNode = aNode->next)
152 OpenGl_PrimitiveArray* aPrimArray = dynamic_cast<OpenGl_PrimitiveArray*> (aNode->elem);
154 if (aPrimArray != NULL)
156 anArrayIDs.insert (aPrimArray->GetUID());
161 else if (theMode == OpenGl_GUM_REBUILD)
163 if (!aStructure->IsRaytracable())
167 else if (addRaytraceStructure (aStructure, theGlContext))
169 anElements.insert (aStructure); // structure was processed
176 if (theMode == OpenGl_GUM_PREPARE)
178 BVH_ObjectSet<Standard_ShortReal, 3>::BVH_ObjectList anUnchangedObjects;
180 // Filter out unchanged objects so only their transformations and materials
181 // will be updated (and newly added objects will be processed from scratch)
182 for (Standard_Integer anObjIdx = 0; anObjIdx < myRaytraceGeometry.Size(); ++anObjIdx)
184 OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
185 myRaytraceGeometry.Objects().ChangeValue (anObjIdx).operator->());
187 if (aTriangleSet == NULL)
192 if (anArrayIDs.find (aTriangleSet->AssociatedPArrayID()) != anArrayIDs.end())
194 anUnchangedObjects.Append (myRaytraceGeometry.Objects().Value (anObjIdx));
196 myArrayToTrianglesMap[aTriangleSet->AssociatedPArrayID()] = aTriangleSet;
200 myRaytraceGeometry.Objects() = anUnchangedObjects;
202 return updateRaytraceGeometry (OpenGl_GUM_REBUILD, theViewId, theGlContext);
204 else if (theMode == OpenGl_GUM_REBUILD)
206 // Actualize the hash map of structures - remove out-of-date records
207 std::map<const OpenGl_Structure*, StructState>::iterator anIter = myStructureStates.begin();
209 while (anIter != myStructureStates.end())
211 if (anElements.find (anIter->first) == anElements.end())
213 myStructureStates.erase (anIter++);
221 // Actualize OpenGL layer list state
222 myRaytraceLayerListState = myZLayers.ModificationStateOfRaytracable();
224 // Rebuild two-level acceleration structure
225 myRaytraceGeometry.ProcessAcceleration();
227 myRaytraceSceneRadius = 2.f /* scale factor */ * std::max (
228 myRaytraceGeometry.Box().CornerMin().cwiseAbs().maxComp(),
229 myRaytraceGeometry.Box().CornerMax().cwiseAbs().maxComp());
231 const BVH_Vec3f aSize = myRaytraceGeometry.Box().Size();
233 myRaytraceSceneEpsilon = Max (1.0e-6f, 1.0e-4f * aSize.Modulus());
235 return uploadRaytraceData (theGlContext);
238 if (myRaytraceParameters.GlobalIllumination)
240 Standard_Boolean toRestart =
241 aNonRaytraceIDs.size() != myNonRaytraceStructureIDs.size();
243 for (std::set<Standard_Integer>::iterator anID = aNonRaytraceIDs.begin(); anID != aNonRaytraceIDs.end() && !toRestart; ++anID)
245 if (myNonRaytraceStructureIDs.find (*anID) == myNonRaytraceStructureIDs.end())
247 toRestart = Standard_True;
256 myNonRaytraceStructureIDs = aNonRaytraceIDs;
259 return Standard_True;
262 // =======================================================================
263 // function : toUpdateStructure
264 // purpose : Checks to see if the structure is modified
265 // =======================================================================
266 Standard_Boolean OpenGl_View::toUpdateStructure (const OpenGl_Structure* theStructure)
268 if (!theStructure->IsRaytracable())
270 if (theStructure->ModificationState() > 0)
272 theStructure->ResetModificationState();
274 return Standard_True; // ray-trace element was removed - need to rebuild
277 return Standard_False; // did not contain ray-trace elements
280 std::map<const OpenGl_Structure*, StructState>::iterator aStructState = myStructureStates.find (theStructure);
282 if (aStructState == myStructureStates.end() || aStructState->second.StructureState != theStructure->ModificationState())
284 return Standard_True;
286 else if (theStructure->InstancedStructure() != NULL)
288 return aStructState->second.InstancedState != theStructure->InstancedStructure()->ModificationState();
291 return Standard_False;
294 // =======================================================================
295 // function : buildTextureTransform
296 // purpose : Constructs texture transformation matrix
297 // =======================================================================
298 void buildTextureTransform (const Handle(Graphic3d_TextureParams)& theParams, BVH_Mat4f& theMatrix)
300 theMatrix.InitIdentity();
301 if (theParams.IsNull())
307 const Graphic3d_Vec2& aScale = theParams->Scale();
309 theMatrix.ChangeValue (0, 0) *= aScale.x();
310 theMatrix.ChangeValue (1, 0) *= aScale.x();
311 theMatrix.ChangeValue (2, 0) *= aScale.x();
312 theMatrix.ChangeValue (3, 0) *= aScale.x();
314 theMatrix.ChangeValue (0, 1) *= aScale.y();
315 theMatrix.ChangeValue (1, 1) *= aScale.y();
316 theMatrix.ChangeValue (2, 1) *= aScale.y();
317 theMatrix.ChangeValue (3, 1) *= aScale.y();
320 const Graphic3d_Vec2 aTrans = -theParams->Translation();
322 theMatrix.ChangeValue (0, 3) = theMatrix.GetValue (0, 0) * aTrans.x() +
323 theMatrix.GetValue (0, 1) * aTrans.y();
325 theMatrix.ChangeValue (1, 3) = theMatrix.GetValue (1, 0) * aTrans.x() +
326 theMatrix.GetValue (1, 1) * aTrans.y();
328 theMatrix.ChangeValue (2, 3) = theMatrix.GetValue (2, 0) * aTrans.x() +
329 theMatrix.GetValue (2, 1) * aTrans.y();
332 const Standard_ShortReal aSin = std::sin (
333 -theParams->Rotation() * static_cast<Standard_ShortReal> (M_PI / 180.0));
334 const Standard_ShortReal aCos = std::cos (
335 -theParams->Rotation() * static_cast<Standard_ShortReal> (M_PI / 180.0));
337 BVH_Mat4f aRotationMat;
338 aRotationMat.SetValue (0, 0, aCos);
339 aRotationMat.SetValue (1, 1, aCos);
340 aRotationMat.SetValue (0, 1, -aSin);
341 aRotationMat.SetValue (1, 0, aSin);
343 theMatrix = theMatrix * aRotationMat;
346 // =======================================================================
347 // function : convertMaterial
348 // purpose : Creates ray-tracing material properties
349 // =======================================================================
350 OpenGl_RaytraceMaterial OpenGl_View::convertMaterial (const OpenGl_Aspects* theAspect,
351 const Handle(OpenGl_Context)& theGlContext)
353 OpenGl_RaytraceMaterial aResMat;
355 const Graphic3d_MaterialAspect& aSrcMat = theAspect->Aspect()->FrontMaterial();
356 const OpenGl_Vec3& aMatCol = theAspect->Aspect()->InteriorColor();
357 const float aShine = 128.0f * float(aSrcMat.Shininess());
359 const OpenGl_Vec3& aSrcAmb = aSrcMat.AmbientColor();
360 const OpenGl_Vec3& aSrcDif = aSrcMat.DiffuseColor();
361 const OpenGl_Vec3& aSrcSpe = aSrcMat.SpecularColor();
362 const OpenGl_Vec3& aSrcEms = aSrcMat.EmissiveColor();
363 switch (aSrcMat.MaterialType())
365 case Graphic3d_MATERIAL_ASPECT:
367 aResMat.Ambient .SetValues (aSrcAmb * aMatCol, 1.0f);
368 aResMat.Diffuse .SetValues (aSrcDif * aMatCol, -1.0f); // -1 is no texture
369 aResMat.Emission.SetValues (aSrcEms * aMatCol, 1.0f);
372 case Graphic3d_MATERIAL_PHYSIC:
374 aResMat.Ambient .SetValues (aSrcAmb, 1.0f);
375 aResMat.Diffuse .SetValues (aSrcDif, -1.0f); // -1 is no texture
376 aResMat.Emission.SetValues (aSrcEms, 1.0f);
382 // interior color is always ignored for Specular
383 aResMat.Specular.SetValues (aSrcSpe, aShine);
384 const Standard_ShortReal aMaxRefl = Max (aResMat.Diffuse.x() + aResMat.Specular.x(),
385 Max (aResMat.Diffuse.y() + aResMat.Specular.y(),
386 aResMat.Diffuse.z() + aResMat.Specular.z()));
387 const Standard_ShortReal aReflectionScale = 0.75f / aMaxRefl;
388 aResMat.Reflection.SetValues (aSrcSpe * aReflectionScale, 0.0f);
391 const float anIndex = (float )aSrcMat.RefractionIndex();
392 aResMat.Transparency = BVH_Vec4f (aSrcMat.Alpha(), aSrcMat.Transparency(),
393 anIndex == 0 ? 1.0f : anIndex,
394 anIndex == 0 ? 1.0f : 1.0f / anIndex);
396 // Serialize physically-based material properties
397 const Graphic3d_BSDF& aBSDF = aSrcMat.BSDF();
399 aResMat.BSDF.Kc = aBSDF.Kc;
400 aResMat.BSDF.Ks = aBSDF.Ks;
401 aResMat.BSDF.Kd = BVH_Vec4f (aBSDF.Kd, -1.f); // no texture
402 aResMat.BSDF.Kt = BVH_Vec4f (aBSDF.Kt, 0.f);
403 aResMat.BSDF.Le = BVH_Vec4f (aBSDF.Le, 0.f);
405 aResMat.BSDF.Absorption = aBSDF.Absorption;
407 aResMat.BSDF.FresnelCoat = aBSDF.FresnelCoat.Serialize ();
408 aResMat.BSDF.FresnelBase = aBSDF.FresnelBase.Serialize ();
410 // Handle material textures
411 if (!theAspect->Aspect()->ToMapTexture())
416 const Handle(OpenGl_TextureSet)& aTextureSet = theAspect->TextureSet (theGlContext);
417 if (aTextureSet.IsNull()
418 || aTextureSet->IsEmpty()
419 || aTextureSet->First().IsNull())
424 if (theGlContext->HasRayTracingTextures())
426 const Handle(OpenGl_Texture)& aTexture = aTextureSet->First();
427 buildTextureTransform (aTexture->Sampler()->Parameters(), aResMat.TextureTransform);
429 // write texture ID to diffuse w-component
430 aResMat.Diffuse.w() = aResMat.BSDF.Kd.w() = static_cast<Standard_ShortReal> (myRaytraceGeometry.AddTexture (aTexture));
432 else if (!myIsRaytraceWarnTextures)
434 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_PORTABILITY, 0, GL_DEBUG_SEVERITY_HIGH,
435 "Warning: texturing in Ray-Trace requires GL_ARB_bindless_texture extension which is missing. "
436 "Please try to update graphics card driver. At the moment textures will be ignored.");
437 myIsRaytraceWarnTextures = Standard_True;
443 // =======================================================================
444 // function : addRaytraceStructure
445 // purpose : Adds OpenGL structure to ray-traced scene geometry
446 // =======================================================================
447 Standard_Boolean OpenGl_View::addRaytraceStructure (const OpenGl_Structure* theStructure,
448 const Handle(OpenGl_Context)& theGlContext)
450 if (!theStructure->IsVisible())
452 myStructureStates[theStructure] = StructState (theStructure);
454 return Standard_True;
457 // Get structure material
458 OpenGl_RaytraceMaterial aDefaultMaterial;
459 Standard_Boolean aResult = addRaytraceGroups (theStructure, aDefaultMaterial, theStructure->Transformation(), theGlContext);
461 // Process all connected OpenGL structures
462 const OpenGl_Structure* anInstanced = theStructure->InstancedStructure();
464 if (anInstanced != NULL && anInstanced->IsRaytracable())
466 aResult &= addRaytraceGroups (anInstanced, aDefaultMaterial, theStructure->Transformation(), theGlContext);
469 myStructureStates[theStructure] = StructState (theStructure);
474 // =======================================================================
475 // function : addRaytraceGroups
476 // purpose : Adds OpenGL groups to ray-traced scene geometry
477 // =======================================================================
478 Standard_Boolean OpenGl_View::addRaytraceGroups (const OpenGl_Structure* theStructure,
479 const OpenGl_RaytraceMaterial& theStructMat,
480 const Handle(Geom_Transformation)& theTrsf,
481 const Handle(OpenGl_Context)& theGlContext)
484 for (OpenGl_Structure::GroupIterator aGroupIter (theStructure->Groups()); aGroupIter.More(); aGroupIter.Next())
486 // Get group material
487 OpenGl_RaytraceMaterial aGroupMaterial;
488 if (aGroupIter.Value()->GlAspects() != NULL)
490 aGroupMaterial = convertMaterial (aGroupIter.Value()->GlAspects(), theGlContext);
493 Standard_Integer aMatID = static_cast<Standard_Integer> (myRaytraceGeometry.Materials.size());
495 // Use group material if available, otherwise use structure material
496 myRaytraceGeometry.Materials.push_back (aGroupIter.Value()->GlAspects() != NULL ? aGroupMaterial : theStructMat);
498 // Add OpenGL elements from group (extract primitives arrays and aspects)
499 for (const OpenGl_ElementNode* aNode = aGroupIter.Value()->FirstNode(); aNode != NULL; aNode = aNode->next)
501 OpenGl_Aspects* anAspect = dynamic_cast<OpenGl_Aspects*> (aNode->elem);
503 if (anAspect != NULL)
505 aMatID = static_cast<Standard_Integer> (myRaytraceGeometry.Materials.size());
507 OpenGl_RaytraceMaterial aMaterial = convertMaterial (anAspect, theGlContext);
509 myRaytraceGeometry.Materials.push_back (aMaterial);
513 OpenGl_PrimitiveArray* aPrimArray = dynamic_cast<OpenGl_PrimitiveArray*> (aNode->elem);
515 if (aPrimArray != NULL)
517 std::map<Standard_Size, OpenGl_TriangleSet*>::iterator aSetIter = myArrayToTrianglesMap.find (aPrimArray->GetUID());
519 if (aSetIter != myArrayToTrianglesMap.end())
521 OpenGl_TriangleSet* aSet = aSetIter->second;
522 opencascade::handle<BVH_Transform<Standard_ShortReal, 4> > aTransform = new BVH_Transform<Standard_ShortReal, 4>();
523 if (!theTrsf.IsNull())
525 theTrsf->Trsf().GetMat4 (aMat4);
526 aTransform->SetTransform (aMat4);
529 aSet->SetProperties (aTransform);
530 if (aSet->MaterialIndex() != OpenGl_TriangleSet::INVALID_MATERIAL && aSet->MaterialIndex() != aMatID)
532 aSet->SetMaterialIndex (aMatID);
537 if (Handle(OpenGl_TriangleSet) aSet = addRaytracePrimitiveArray (aPrimArray, aMatID, 0))
539 opencascade::handle<BVH_Transform<Standard_ShortReal, 4> > aTransform = new BVH_Transform<Standard_ShortReal, 4>();
540 if (!theTrsf.IsNull())
542 theTrsf->Trsf().GetMat4 (aMat4);
543 aTransform->SetTransform (aMat4);
546 aSet->SetProperties (aTransform);
547 myRaytraceGeometry.Objects().Append (aSet);
555 return Standard_True;
558 // =======================================================================
559 // function : addRaytracePrimitiveArray
560 // purpose : Adds OpenGL primitive array to ray-traced scene geometry
561 // =======================================================================
562 Handle(OpenGl_TriangleSet) OpenGl_View::addRaytracePrimitiveArray (const OpenGl_PrimitiveArray* theArray,
563 const Standard_Integer theMaterial,
564 const OpenGl_Mat4* theTransform)
566 const Handle(Graphic3d_BoundBuffer)& aBounds = theArray->Bounds();
567 const Handle(Graphic3d_IndexBuffer)& anIndices = theArray->Indices();
568 const Handle(Graphic3d_Buffer)& anAttribs = theArray->Attributes();
570 if (theArray->DrawMode() < GL_TRIANGLES
571 #ifndef GL_ES_VERSION_2_0
572 || theArray->DrawMode() > GL_POLYGON
574 || theArray->DrawMode() > GL_TRIANGLE_FAN
576 || anAttribs.IsNull())
578 return Handle(OpenGl_TriangleSet)();
581 OpenGl_Mat4 aNormalMatrix;
582 if (theTransform != NULL)
584 Standard_ASSERT_RETURN (theTransform->Inverted (aNormalMatrix),
585 "Error: Failed to compute normal transformation matrix", NULL);
587 aNormalMatrix.Transpose();
590 Handle(OpenGl_TriangleSet) aSet = new OpenGl_TriangleSet (theArray->GetUID(), myRaytraceBVHBuilder);
592 aSet->Vertices.reserve (anAttribs->NbElements);
593 aSet->Normals.reserve (anAttribs->NbElements);
594 aSet->TexCrds.reserve (anAttribs->NbElements);
596 const size_t aVertFrom = aSet->Vertices.size();
598 Standard_Integer anAttribIndex = 0;
599 Standard_Size anAttribStride = 0;
600 if (const Standard_Byte* aPosData = anAttribs->AttributeData (Graphic3d_TOA_POS, anAttribIndex, anAttribStride))
602 const Graphic3d_Attribute& anAttrib = anAttribs->Attribute (anAttribIndex);
603 if (anAttrib.DataType == Graphic3d_TOD_VEC2
604 || anAttrib.DataType == Graphic3d_TOD_VEC3
605 || anAttrib.DataType == Graphic3d_TOD_VEC4)
607 for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
609 const float* aCoords = reinterpret_cast<const float*> (aPosData + anAttribStride * aVertIter);
610 aSet->Vertices.push_back (BVH_Vec3f (aCoords[0], aCoords[1], anAttrib.DataType != Graphic3d_TOD_VEC2 ? aCoords[2] : 0.0f));
614 if (const Standard_Byte* aNormData = anAttribs->AttributeData (Graphic3d_TOA_NORM, anAttribIndex, anAttribStride))
616 const Graphic3d_Attribute& anAttrib = anAttribs->Attribute (anAttribIndex);
617 if (anAttrib.DataType == Graphic3d_TOD_VEC3
618 || anAttrib.DataType == Graphic3d_TOD_VEC4)
620 for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
622 aSet->Normals.push_back (*reinterpret_cast<const Graphic3d_Vec3*> (aNormData + anAttribStride * aVertIter));
626 if (const Standard_Byte* aTexData = anAttribs->AttributeData (Graphic3d_TOA_UV, anAttribIndex, anAttribStride))
628 const Graphic3d_Attribute& anAttrib = anAttribs->Attribute (anAttribIndex);
629 if (anAttrib.DataType == Graphic3d_TOD_VEC2)
631 for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
633 aSet->TexCrds.push_back (*reinterpret_cast<const Graphic3d_Vec2*> (aTexData + anAttribStride * aVertIter));
638 if (aSet->Normals.size() != aSet->Vertices.size())
640 for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
642 aSet->Normals.push_back (BVH_Vec3f());
646 if (aSet->TexCrds.size() != aSet->Vertices.size())
648 for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
650 aSet->TexCrds.push_back (BVH_Vec2f());
654 if (theTransform != NULL)
656 for (size_t aVertIter = aVertFrom; aVertIter < aSet->Vertices.size(); ++aVertIter)
658 BVH_Vec3f& aVertex = aSet->Vertices[aVertIter];
660 BVH_Vec4f aTransVertex = *theTransform *
661 BVH_Vec4f (aVertex.x(), aVertex.y(), aVertex.z(), 1.f);
663 aVertex = BVH_Vec3f (aTransVertex.x(), aTransVertex.y(), aTransVertex.z());
665 for (size_t aVertIter = aVertFrom; aVertIter < aSet->Normals.size(); ++aVertIter)
667 BVH_Vec3f& aNormal = aSet->Normals[aVertIter];
669 BVH_Vec4f aTransNormal = aNormalMatrix *
670 BVH_Vec4f (aNormal.x(), aNormal.y(), aNormal.z(), 0.f);
672 aNormal = BVH_Vec3f (aTransNormal.x(), aTransNormal.y(), aTransNormal.z());
676 if (!aBounds.IsNull())
678 for (Standard_Integer aBound = 0, aBoundStart = 0; aBound < aBounds->NbBounds; ++aBound)
680 const Standard_Integer aVertNum = aBounds->Bounds[aBound];
682 if (!addRaytraceVertexIndices (*aSet, theMaterial, aVertNum, aBoundStart, *theArray))
685 return Handle(OpenGl_TriangleSet)();
688 aBoundStart += aVertNum;
693 const Standard_Integer aVertNum = !anIndices.IsNull() ? anIndices->NbElements : anAttribs->NbElements;
695 if (!addRaytraceVertexIndices (*aSet, theMaterial, aVertNum, 0, *theArray))
698 return Handle(OpenGl_TriangleSet)();
703 if (aSet->Size() != 0)
711 // =======================================================================
712 // function : addRaytraceVertexIndices
713 // purpose : Adds vertex indices to ray-traced scene geometry
714 // =======================================================================
715 Standard_Boolean OpenGl_View::addRaytraceVertexIndices (OpenGl_TriangleSet& theSet,
716 const Standard_Integer theMatID,
717 const Standard_Integer theCount,
718 const Standard_Integer theOffset,
719 const OpenGl_PrimitiveArray& theArray)
721 switch (theArray.DrawMode())
723 case GL_TRIANGLES: return addRaytraceTriangleArray (theSet, theMatID, theCount, theOffset, theArray.Indices());
724 case GL_TRIANGLE_FAN: return addRaytraceTriangleFanArray (theSet, theMatID, theCount, theOffset, theArray.Indices());
725 case GL_TRIANGLE_STRIP: return addRaytraceTriangleStripArray (theSet, theMatID, theCount, theOffset, theArray.Indices());
726 #if !defined(GL_ES_VERSION_2_0)
727 case GL_QUAD_STRIP: return addRaytraceQuadrangleStripArray (theSet, theMatID, theCount, theOffset, theArray.Indices());
728 case GL_QUADS: return addRaytraceQuadrangleArray (theSet, theMatID, theCount, theOffset, theArray.Indices());
729 case GL_POLYGON: return addRaytracePolygonArray (theSet, theMatID, theCount, theOffset, theArray.Indices());
733 return Standard_False;
736 // =======================================================================
737 // function : addRaytraceTriangleArray
738 // purpose : Adds OpenGL triangle array to ray-traced scene geometry
739 // =======================================================================
740 Standard_Boolean OpenGl_View::addRaytraceTriangleArray (OpenGl_TriangleSet& theSet,
741 const Standard_Integer theMatID,
742 const Standard_Integer theCount,
743 const Standard_Integer theOffset,
744 const Handle(Graphic3d_IndexBuffer)& theIndices)
748 return Standard_True;
751 theSet.Elements.reserve (theSet.Elements.size() + theCount / 3);
753 if (!theIndices.IsNull())
755 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; aVert += 3)
757 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0),
758 theIndices->Index (aVert + 1),
759 theIndices->Index (aVert + 2),
765 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; aVert += 3)
767 theSet.Elements.push_back (BVH_Vec4i (aVert + 0, aVert + 1, aVert + 2, theMatID));
771 return Standard_True;
774 // =======================================================================
775 // function : addRaytraceTriangleFanArray
776 // purpose : Adds OpenGL triangle fan array to ray-traced scene geometry
777 // =======================================================================
778 Standard_Boolean OpenGl_View::addRaytraceTriangleFanArray (OpenGl_TriangleSet& theSet,
779 const Standard_Integer theMatID,
780 const Standard_Integer theCount,
781 const Standard_Integer theOffset,
782 const Handle(Graphic3d_IndexBuffer)& theIndices)
786 return Standard_True;
789 theSet.Elements.reserve (theSet.Elements.size() + theCount - 2);
791 if (!theIndices.IsNull())
793 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
795 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (theOffset),
796 theIndices->Index (aVert + 1),
797 theIndices->Index (aVert + 2),
803 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
805 theSet.Elements.push_back (BVH_Vec4i (theOffset,
812 return Standard_True;
815 // =======================================================================
816 // function : addRaytraceTriangleStripArray
817 // purpose : Adds OpenGL triangle strip array to ray-traced scene geometry
818 // =======================================================================
819 Standard_Boolean OpenGl_View::addRaytraceTriangleStripArray (OpenGl_TriangleSet& theSet,
820 const Standard_Integer theMatID,
821 const Standard_Integer theCount,
822 const Standard_Integer theOffset,
823 const Handle(Graphic3d_IndexBuffer)& theIndices)
827 return Standard_True;
830 theSet.Elements.reserve (theSet.Elements.size() + theCount - 2);
832 if (!theIndices.IsNull())
834 for (Standard_Integer aVert = theOffset, aCW = 0; aVert < theOffset + theCount - 2; ++aVert, aCW = (aCW + 1) % 2)
836 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + (aCW ? 1 : 0)),
837 theIndices->Index (aVert + (aCW ? 0 : 1)),
838 theIndices->Index (aVert + 2),
844 for (Standard_Integer aVert = theOffset, aCW = 0; aVert < theOffset + theCount - 2; ++aVert, aCW = (aCW + 1) % 2)
846 theSet.Elements.push_back (BVH_Vec4i (aVert + (aCW ? 1 : 0),
847 aVert + (aCW ? 0 : 1),
853 return Standard_True;
856 // =======================================================================
857 // function : addRaytraceQuadrangleArray
858 // purpose : Adds OpenGL quad array to ray-traced scene geometry
859 // =======================================================================
860 Standard_Boolean OpenGl_View::addRaytraceQuadrangleArray (OpenGl_TriangleSet& theSet,
861 const Standard_Integer theMatID,
862 const Standard_Integer theCount,
863 const Standard_Integer theOffset,
864 const Handle(Graphic3d_IndexBuffer)& theIndices)
868 return Standard_True;
871 theSet.Elements.reserve (theSet.Elements.size() + theCount / 2);
873 if (!theIndices.IsNull())
875 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 4)
877 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0),
878 theIndices->Index (aVert + 1),
879 theIndices->Index (aVert + 2),
881 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0),
882 theIndices->Index (aVert + 2),
883 theIndices->Index (aVert + 3),
889 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 4)
891 theSet.Elements.push_back (BVH_Vec4i (aVert + 0, aVert + 1, aVert + 2,
893 theSet.Elements.push_back (BVH_Vec4i (aVert + 0, aVert + 2, aVert + 3,
898 return Standard_True;
901 // =======================================================================
902 // function : addRaytraceQuadrangleStripArray
903 // purpose : Adds OpenGL quad strip array to ray-traced scene geometry
904 // =======================================================================
905 Standard_Boolean OpenGl_View::addRaytraceQuadrangleStripArray (OpenGl_TriangleSet& theSet,
906 const Standard_Integer theMatID,
907 const Standard_Integer theCount,
908 const Standard_Integer theOffset,
909 const Handle(Graphic3d_IndexBuffer)& theIndices)
913 return Standard_True;
916 theSet.Elements.reserve (theSet.Elements.size() + 2 * theCount - 6);
918 if (!theIndices.IsNull())
920 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 2)
922 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0),
923 theIndices->Index (aVert + 1),
924 theIndices->Index (aVert + 2),
927 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 1),
928 theIndices->Index (aVert + 3),
929 theIndices->Index (aVert + 2),
935 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 2)
937 theSet.Elements.push_back (BVH_Vec4i (aVert + 0,
942 theSet.Elements.push_back (BVH_Vec4i (aVert + 1,
949 return Standard_True;
952 // =======================================================================
953 // function : addRaytracePolygonArray
954 // purpose : Adds OpenGL polygon array to ray-traced scene geometry
955 // =======================================================================
956 Standard_Boolean OpenGl_View::addRaytracePolygonArray (OpenGl_TriangleSet& theSet,
957 const Standard_Integer theMatID,
958 const Standard_Integer theCount,
959 const Standard_Integer theOffset,
960 const Handle(Graphic3d_IndexBuffer)& theIndices)
964 return Standard_True;
967 theSet.Elements.reserve (theSet.Elements.size() + theCount - 2);
969 if (!theIndices.IsNull())
971 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
973 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (theOffset),
974 theIndices->Index (aVert + 1),
975 theIndices->Index (aVert + 2),
981 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
983 theSet.Elements.push_back (BVH_Vec4i (theOffset,
990 return Standard_True;
993 const TCollection_AsciiString OpenGl_View::ShaderSource::EMPTY_PREFIX;
995 // =======================================================================
997 // purpose : Returns shader source combined with prefix
998 // =======================================================================
999 TCollection_AsciiString OpenGl_View::ShaderSource::Source() const
1001 const TCollection_AsciiString aVersion = "#version 140";
1003 if (myPrefix.IsEmpty())
1005 return aVersion + "\n" + mySource;
1008 return aVersion + "\n" + myPrefix + "\n" + mySource;
1011 // =======================================================================
1012 // function : LoadFromFiles
1013 // purpose : Loads shader source from specified files
1014 // =======================================================================
1015 Standard_Boolean OpenGl_View::ShaderSource::LoadFromFiles (const TCollection_AsciiString* theFileNames,
1016 const TCollection_AsciiString& thePrefix)
1020 myPrefix = thePrefix;
1022 TCollection_AsciiString aMissingFiles;
1023 for (Standard_Integer anIndex = 0; !theFileNames[anIndex].IsEmpty(); ++anIndex)
1025 OSD_File aFile (theFileNames[anIndex]);
1028 aFile.Open (OSD_ReadOnly, OSD_Protection());
1030 if (!aFile.IsOpen())
1032 if (!aMissingFiles.IsEmpty())
1034 aMissingFiles += ", ";
1036 aMissingFiles += TCollection_AsciiString("'") + theFileNames[anIndex] + "'";
1039 else if (!aMissingFiles.IsEmpty())
1045 TCollection_AsciiString aSource;
1046 aFile.Read (aSource, (Standard_Integer) aFile.Size());
1047 if (!aSource.IsEmpty())
1049 mySource += TCollection_AsciiString ("\n") + aSource;
1054 if (!aMissingFiles.IsEmpty())
1056 myError = TCollection_AsciiString("Shader files ") + aMissingFiles + " are missing or inaccessible";
1057 return Standard_False;
1059 return Standard_True;
1062 // =======================================================================
1063 // function : LoadFromStrings
1065 // =======================================================================
1066 Standard_Boolean OpenGl_View::ShaderSource::LoadFromStrings (const TCollection_AsciiString* theStrings,
1067 const TCollection_AsciiString& thePrefix)
1071 myPrefix = thePrefix;
1073 for (Standard_Integer anIndex = 0; !theStrings[anIndex].IsEmpty(); ++anIndex)
1075 TCollection_AsciiString aSource = theStrings[anIndex];
1076 if (!aSource.IsEmpty())
1078 mySource += TCollection_AsciiString ("\n") + aSource;
1081 return Standard_True;
1084 // =======================================================================
1085 // function : generateShaderPrefix
1086 // purpose : Generates shader prefix based on current ray-tracing options
1087 // =======================================================================
1088 TCollection_AsciiString OpenGl_View::generateShaderPrefix (const Handle(OpenGl_Context)& theGlContext) const
1090 TCollection_AsciiString aPrefixString =
1091 TCollection_AsciiString ("#define STACK_SIZE ") + TCollection_AsciiString (myRaytraceParameters.StackSize) + "\n" +
1092 TCollection_AsciiString ("#define NB_BOUNCES ") + TCollection_AsciiString (myRaytraceParameters.NbBounces);
1094 if (myRaytraceParameters.TransparentShadows)
1096 aPrefixString += TCollection_AsciiString ("\n#define TRANSPARENT_SHADOWS");
1099 // If OpenGL driver supports bindless textures and texturing
1100 // is actually used, activate texturing in ray-tracing mode
1101 if (myRaytraceParameters.UseBindlessTextures && theGlContext->arbTexBindless != NULL)
1103 aPrefixString += TCollection_AsciiString ("\n#define USE_TEXTURES") +
1104 TCollection_AsciiString ("\n#define MAX_TEX_NUMBER ") + TCollection_AsciiString (OpenGl_RaytraceGeometry::MAX_TEX_NUMBER);
1107 if (myRaytraceParameters.GlobalIllumination) // path tracing activated
1109 aPrefixString += TCollection_AsciiString ("\n#define PATH_TRACING");
1111 if (myRaytraceParameters.AdaptiveScreenSampling) // adaptive screen sampling requested
1113 if (theGlContext->IsGlGreaterEqual (4, 4))
1115 aPrefixString += TCollection_AsciiString ("\n#define ADAPTIVE_SAMPLING");
1116 if (myRaytraceParameters.AdaptiveScreenSamplingAtomic
1117 && theGlContext->CheckExtension ("GL_NV_shader_atomic_float"))
1119 aPrefixString += TCollection_AsciiString ("\n#define ADAPTIVE_SAMPLING_ATOMIC");
1124 if (myRaytraceParameters.TwoSidedBsdfModels) // two-sided BSDFs requested
1126 aPrefixString += TCollection_AsciiString ("\n#define TWO_SIDED_BXDF");
1129 switch (myRaytraceParameters.ToneMappingMethod)
1131 case Graphic3d_ToneMappingMethod_Disabled:
1133 case Graphic3d_ToneMappingMethod_Filmic:
1134 aPrefixString += TCollection_AsciiString ("\n#define TONE_MAPPING_FILMIC");
1139 if (myRaytraceParameters.DepthOfField)
1141 aPrefixString += TCollection_AsciiString("\n#define DEPTH_OF_FIELD");
1144 return aPrefixString;
1147 // =======================================================================
1148 // function : safeFailBack
1149 // purpose : Performs safe exit when shaders initialization fails
1150 // =======================================================================
1151 Standard_Boolean OpenGl_View::safeFailBack (const TCollection_ExtendedString& theMessage,
1152 const Handle(OpenGl_Context)& theGlContext)
1154 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1155 GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, theMessage);
1157 myRaytraceInitStatus = OpenGl_RT_FAIL;
1159 releaseRaytraceResources (theGlContext);
1161 return Standard_False;
1164 // =======================================================================
1165 // function : initShader
1166 // purpose : Creates new shader object with specified source
1167 // =======================================================================
1168 Handle(OpenGl_ShaderObject) OpenGl_View::initShader (const GLenum theType,
1169 const ShaderSource& theSource,
1170 const Handle(OpenGl_Context)& theGlContext)
1172 Handle(OpenGl_ShaderObject) aShader = new OpenGl_ShaderObject (theType);
1173 if (!aShader->Create (theGlContext))
1175 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH,
1176 TCollection_ExtendedString ("Error: Failed to create ") +
1177 (theType == GL_VERTEX_SHADER ? "vertex" : "fragment") + " shader object");
1178 aShader->Release (theGlContext.get());
1179 return Handle(OpenGl_ShaderObject)();
1182 if (!aShader->LoadAndCompile (theGlContext, "", theSource.Source()))
1184 aShader->Release (theGlContext.get());
1185 return Handle(OpenGl_ShaderObject)();
1190 // =======================================================================
1191 // function : initProgram
1192 // purpose : Creates GLSL program from the given shader objects
1193 // =======================================================================
1194 Handle(OpenGl_ShaderProgram) OpenGl_View::initProgram (const Handle(OpenGl_Context)& theGlContext,
1195 const Handle(OpenGl_ShaderObject)& theVertShader,
1196 const Handle(OpenGl_ShaderObject)& theFragShader,
1197 const TCollection_AsciiString& theName)
1199 const TCollection_AsciiString anId = TCollection_AsciiString("occt_rt_") + theName;
1200 Handle(OpenGl_ShaderProgram) aProgram = new OpenGl_ShaderProgram(Handle(Graphic3d_ShaderProgram)(), anId);
1202 if (!aProgram->Create (theGlContext))
1204 theVertShader->Release (theGlContext.operator->());
1206 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1207 GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, "Failed to create shader program");
1209 return Handle(OpenGl_ShaderProgram)();
1212 if (!aProgram->AttachShader (theGlContext, theVertShader)
1213 || !aProgram->AttachShader (theGlContext, theFragShader))
1215 theVertShader->Release (theGlContext.operator->());
1217 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1218 GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, "Failed to attach shader objects");
1220 return Handle(OpenGl_ShaderProgram)();
1223 aProgram->SetAttributeName (theGlContext, Graphic3d_TOA_POS, "occVertex");
1225 TCollection_AsciiString aLinkLog;
1227 if (!aProgram->Link (theGlContext))
1229 aProgram->FetchInfoLog (theGlContext, aLinkLog);
1231 const TCollection_ExtendedString aMessage = TCollection_ExtendedString (
1232 "Failed to link shader program:\n") + aLinkLog;
1234 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1235 GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, aMessage);
1237 return Handle(OpenGl_ShaderProgram)();
1239 else if (theGlContext->caps->glslWarnings)
1241 aProgram->FetchInfoLog (theGlContext, aLinkLog);
1242 if (!aLinkLog.IsEmpty() && !aLinkLog.IsEqual ("No errors.\n"))
1244 const TCollection_ExtendedString aMessage = TCollection_ExtendedString (
1245 "Shader program was linked with following warnings:\n") + aLinkLog;
1247 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1248 GL_DEBUG_TYPE_PORTABILITY, 0, GL_DEBUG_SEVERITY_LOW, aMessage);
1255 // =======================================================================
1256 // function : initRaytraceResources
1257 // purpose : Initializes OpenGL/GLSL shader programs
1258 // =======================================================================
1259 Standard_Boolean OpenGl_View::initRaytraceResources (const Standard_Integer theSizeX,
1260 const Standard_Integer theSizeY,
1261 const Handle(OpenGl_Context)& theGlContext)
1263 if (myRaytraceInitStatus == OpenGl_RT_FAIL)
1265 return Standard_False;
1268 Standard_Boolean aToRebuildShaders = Standard_False;
1270 if (myRenderParams.RebuildRayTracingShaders) // requires complete re-initialization
1272 myRaytraceInitStatus = OpenGl_RT_NONE;
1273 releaseRaytraceResources (theGlContext, Standard_True);
1274 myRenderParams.RebuildRayTracingShaders = Standard_False; // clear rebuilding flag
1277 if (myRaytraceInitStatus == OpenGl_RT_INIT)
1279 if (!myIsRaytraceDataValid)
1281 return Standard_True;
1284 const Standard_Integer aRequiredStackSize =
1285 myRaytraceGeometry.TopLevelTreeDepth() + myRaytraceGeometry.BotLevelTreeDepth();
1287 if (myRaytraceParameters.StackSize < aRequiredStackSize)
1289 myRaytraceParameters.StackSize = Max (aRequiredStackSize, THE_DEFAULT_STACK_SIZE);
1291 aToRebuildShaders = Standard_True;
1295 if (aRequiredStackSize < myRaytraceParameters.StackSize)
1297 if (myRaytraceParameters.StackSize > THE_DEFAULT_STACK_SIZE)
1299 myRaytraceParameters.StackSize = Max (aRequiredStackSize, THE_DEFAULT_STACK_SIZE);
1300 aToRebuildShaders = Standard_True;
1305 if (myRenderParams.RaytracingDepth != myRaytraceParameters.NbBounces
1306 || myRenderParams.IsTransparentShadowEnabled != myRaytraceParameters.TransparentShadows
1307 || myRenderParams.IsGlobalIlluminationEnabled != myRaytraceParameters.GlobalIllumination
1308 || myRenderParams.TwoSidedBsdfModels != myRaytraceParameters.TwoSidedBsdfModels
1309 || myRaytraceGeometry.HasTextures() != myRaytraceParameters.UseBindlessTextures)
1311 myRaytraceParameters.NbBounces = myRenderParams.RaytracingDepth;
1312 myRaytraceParameters.TransparentShadows = myRenderParams.IsTransparentShadowEnabled;
1313 myRaytraceParameters.GlobalIllumination = myRenderParams.IsGlobalIlluminationEnabled;
1314 myRaytraceParameters.TwoSidedBsdfModels = myRenderParams.TwoSidedBsdfModels;
1315 myRaytraceParameters.UseBindlessTextures = myRaytraceGeometry.HasTextures();
1316 aToRebuildShaders = Standard_True;
1319 if (myRenderParams.AdaptiveScreenSampling != myRaytraceParameters.AdaptiveScreenSampling
1320 || myRenderParams.AdaptiveScreenSamplingAtomic != myRaytraceParameters.AdaptiveScreenSamplingAtomic)
1322 myRaytraceParameters.AdaptiveScreenSampling = myRenderParams.AdaptiveScreenSampling;
1323 myRaytraceParameters.AdaptiveScreenSamplingAtomic = myRenderParams.AdaptiveScreenSamplingAtomic;
1324 if (myRenderParams.AdaptiveScreenSampling) // adaptive sampling was requested
1326 if (!theGlContext->HasRayTracingAdaptiveSampling())
1328 // disable the feature if it is not supported
1329 myRaytraceParameters.AdaptiveScreenSampling = myRenderParams.AdaptiveScreenSampling = Standard_False;
1330 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_PORTABILITY, 0, GL_DEBUG_SEVERITY_LOW,
1331 "Adaptive sampling is not supported (OpenGL 4.4 is missing)");
1333 else if (myRaytraceParameters.AdaptiveScreenSamplingAtomic
1334 && !theGlContext->HasRayTracingAdaptiveSamplingAtomic())
1336 // disable the feature if it is not supported
1337 myRaytraceParameters.AdaptiveScreenSamplingAtomic = myRenderParams.AdaptiveScreenSamplingAtomic = Standard_False;
1338 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_PORTABILITY, 0, GL_DEBUG_SEVERITY_LOW,
1339 "Atomic adaptive sampling is not supported (GL_NV_shader_atomic_float is missing)");
1343 aToRebuildShaders = Standard_True;
1345 myTileSampler.SetSize (myRenderParams, myRaytraceParameters.AdaptiveScreenSampling ? Graphic3d_Vec2i (theSizeX, theSizeY) : Graphic3d_Vec2i (0, 0));
1347 const bool toEnableDof = !myCamera->IsOrthographic() && myRaytraceParameters.GlobalIllumination;
1348 if (myRaytraceParameters.DepthOfField != toEnableDof)
1350 myRaytraceParameters.DepthOfField = toEnableDof;
1351 aToRebuildShaders = Standard_True;
1354 if (myRenderParams.ToneMappingMethod != myRaytraceParameters.ToneMappingMethod)
1356 myRaytraceParameters.ToneMappingMethod = myRenderParams.ToneMappingMethod;
1357 aToRebuildShaders = true;
1360 if (aToRebuildShaders)
1362 // Reject accumulated frames
1365 // Environment map should be updated
1366 myToUpdateEnvironmentMap = Standard_True;
1368 const TCollection_AsciiString aPrefixString = generateShaderPrefix (theGlContext);
1370 #ifdef RAY_TRACE_PRINT_INFO
1371 std::cout << "GLSL prefix string:" << std::endl << aPrefixString << std::endl;
1374 myRaytraceShaderSource.SetPrefix (aPrefixString);
1375 myPostFSAAShaderSource.SetPrefix (aPrefixString);
1376 myOutImageShaderSource.SetPrefix (aPrefixString);
1378 if (!myRaytraceShader->LoadAndCompile (theGlContext, myRaytraceProgram->ResourceId(), myRaytraceShaderSource.Source())
1379 || !myPostFSAAShader->LoadAndCompile (theGlContext, myPostFSAAProgram->ResourceId(), myPostFSAAShaderSource.Source())
1380 || !myOutImageShader->LoadAndCompile (theGlContext, myOutImageProgram->ResourceId(), myOutImageShaderSource.Source()))
1382 return safeFailBack ("Failed to compile ray-tracing fragment shaders", theGlContext);
1385 myRaytraceProgram->SetAttributeName (theGlContext, Graphic3d_TOA_POS, "occVertex");
1386 myPostFSAAProgram->SetAttributeName (theGlContext, Graphic3d_TOA_POS, "occVertex");
1387 myOutImageProgram->SetAttributeName (theGlContext, Graphic3d_TOA_POS, "occVertex");
1389 if (!myRaytraceProgram->Link (theGlContext)
1390 || !myPostFSAAProgram->Link (theGlContext)
1391 || !myOutImageProgram->Link (theGlContext))
1393 return safeFailBack ("Failed to initialize vertex attributes for ray-tracing program", theGlContext);
1398 if (myRaytraceInitStatus == OpenGl_RT_NONE)
1400 myAccumFrames = 0; // accumulation should be restarted
1402 if (!theGlContext->IsGlGreaterEqual (3, 1))
1404 return safeFailBack ("Ray-tracing requires OpenGL 3.1 and higher", theGlContext);
1406 else if (!theGlContext->arbTboRGB32)
1408 return safeFailBack ("Ray-tracing requires OpenGL 4.0+ or GL_ARB_texture_buffer_object_rgb32 extension", theGlContext);
1410 else if (!theGlContext->arbFBOBlit)
1412 return safeFailBack ("Ray-tracing requires EXT_framebuffer_blit extension", theGlContext);
1415 myRaytraceParameters.NbBounces = myRenderParams.RaytracingDepth;
1417 const TCollection_AsciiString aShaderFolder = Graphic3d_ShaderProgram::ShadersFolder();
1418 if (myIsRaytraceDataValid)
1420 myRaytraceParameters.StackSize = Max (THE_DEFAULT_STACK_SIZE,
1421 myRaytraceGeometry.TopLevelTreeDepth() + myRaytraceGeometry.BotLevelTreeDepth());
1424 const TCollection_AsciiString aPrefixString = generateShaderPrefix (theGlContext);
1426 #ifdef RAY_TRACE_PRINT_INFO
1427 std::cout << "GLSL prefix string:" << std::endl << aPrefixString << std::endl;
1430 ShaderSource aBasicVertShaderSrc;
1432 if (!aShaderFolder.IsEmpty())
1434 const TCollection_AsciiString aFiles[] = { aShaderFolder + "/RaytraceBase.vs", "" };
1435 if (!aBasicVertShaderSrc.LoadFromFiles (aFiles))
1437 return safeFailBack (aBasicVertShaderSrc.ErrorDescription(), theGlContext);
1442 const TCollection_AsciiString aSrcShaders[] = { Shaders_RaytraceBase_vs, "" };
1443 aBasicVertShaderSrc.LoadFromStrings (aSrcShaders);
1448 if (!aShaderFolder.IsEmpty())
1450 const TCollection_AsciiString aFiles[] = { aShaderFolder + "/RaytraceBase.fs",
1451 aShaderFolder + "/PathtraceBase.fs",
1452 aShaderFolder + "/RaytraceRender.fs",
1454 if (!myRaytraceShaderSource.LoadFromFiles (aFiles, aPrefixString))
1456 return safeFailBack (myRaytraceShaderSource.ErrorDescription(), theGlContext);
1461 const TCollection_AsciiString aSrcShaders[] = { Shaders_RaytraceBase_fs,
1462 Shaders_PathtraceBase_fs,
1463 Shaders_RaytraceRender_fs,
1465 myRaytraceShaderSource.LoadFromStrings (aSrcShaders, aPrefixString);
1468 Handle(OpenGl_ShaderObject) aBasicVertShader = initShader (GL_VERTEX_SHADER, aBasicVertShaderSrc, theGlContext);
1469 if (aBasicVertShader.IsNull())
1471 return safeFailBack ("Failed to initialize ray-trace vertex shader", theGlContext);
1474 myRaytraceShader = initShader (GL_FRAGMENT_SHADER, myRaytraceShaderSource, theGlContext);
1475 if (myRaytraceShader.IsNull())
1477 aBasicVertShader->Release (theGlContext.operator->());
1478 return safeFailBack ("Failed to initialize ray-trace fragment shader", theGlContext);
1481 myRaytraceProgram = initProgram (theGlContext, aBasicVertShader, myRaytraceShader, "main");
1482 if (myRaytraceProgram.IsNull())
1484 return safeFailBack ("Failed to initialize ray-trace shader program", theGlContext);
1489 if (!aShaderFolder.IsEmpty())
1491 const TCollection_AsciiString aFiles[] = { aShaderFolder + "/RaytraceBase.fs", aShaderFolder + "/RaytraceSmooth.fs", "" };
1492 if (!myPostFSAAShaderSource.LoadFromFiles (aFiles, aPrefixString))
1494 return safeFailBack (myPostFSAAShaderSource.ErrorDescription(), theGlContext);
1499 const TCollection_AsciiString aSrcShaders[] = { Shaders_RaytraceBase_fs, Shaders_RaytraceSmooth_fs, "" };
1500 myPostFSAAShaderSource.LoadFromStrings (aSrcShaders, aPrefixString);
1503 Handle(OpenGl_ShaderObject) aBasicVertShader = initShader (GL_VERTEX_SHADER, aBasicVertShaderSrc, theGlContext);
1504 if (aBasicVertShader.IsNull())
1506 return safeFailBack ("Failed to initialize FSAA vertex shader", theGlContext);
1509 myPostFSAAShader = initShader (GL_FRAGMENT_SHADER, myPostFSAAShaderSource, theGlContext);
1510 if (myPostFSAAShader.IsNull())
1512 aBasicVertShader->Release (theGlContext.operator->());
1513 return safeFailBack ("Failed to initialize FSAA fragment shader", theGlContext);
1516 myPostFSAAProgram = initProgram (theGlContext, aBasicVertShader, myPostFSAAShader, "fsaa");
1517 if (myPostFSAAProgram.IsNull())
1519 return safeFailBack ("Failed to initialize FSAA shader program", theGlContext);
1524 if (!aShaderFolder.IsEmpty())
1526 const TCollection_AsciiString aFiles[] = { aShaderFolder + "/Display.fs", "" };
1527 if (!myOutImageShaderSource.LoadFromFiles (aFiles, aPrefixString))
1529 return safeFailBack (myOutImageShaderSource.ErrorDescription(), theGlContext);
1534 const TCollection_AsciiString aSrcShaders[] = { Shaders_Display_fs, "" };
1535 myOutImageShaderSource.LoadFromStrings (aSrcShaders, aPrefixString);
1538 Handle(OpenGl_ShaderObject) aBasicVertShader = initShader (GL_VERTEX_SHADER, aBasicVertShaderSrc, theGlContext);
1539 if (aBasicVertShader.IsNull())
1541 return safeFailBack ("Failed to set vertex shader source", theGlContext);
1544 myOutImageShader = initShader (GL_FRAGMENT_SHADER, myOutImageShaderSource, theGlContext);
1545 if (myOutImageShader.IsNull())
1547 aBasicVertShader->Release (theGlContext.operator->());
1548 return safeFailBack ("Failed to set display fragment shader source", theGlContext);
1551 myOutImageProgram = initProgram (theGlContext, aBasicVertShader, myOutImageShader, "out");
1552 if (myOutImageProgram.IsNull())
1554 return safeFailBack ("Failed to initialize display shader program", theGlContext);
1559 if (myRaytraceInitStatus == OpenGl_RT_NONE || aToRebuildShaders)
1561 for (Standard_Integer anIndex = 0; anIndex < 2; ++anIndex)
1563 Handle(OpenGl_ShaderProgram)& aShaderProgram =
1564 (anIndex == 0) ? myRaytraceProgram : myPostFSAAProgram;
1566 theGlContext->BindProgram (aShaderProgram);
1568 aShaderProgram->SetSampler (theGlContext,
1569 "uSceneMinPointTexture", OpenGl_RT_SceneMinPointTexture);
1570 aShaderProgram->SetSampler (theGlContext,
1571 "uSceneMaxPointTexture", OpenGl_RT_SceneMaxPointTexture);
1572 aShaderProgram->SetSampler (theGlContext,
1573 "uSceneNodeInfoTexture", OpenGl_RT_SceneNodeInfoTexture);
1574 aShaderProgram->SetSampler (theGlContext,
1575 "uGeometryVertexTexture", OpenGl_RT_GeometryVertexTexture);
1576 aShaderProgram->SetSampler (theGlContext,
1577 "uGeometryNormalTexture", OpenGl_RT_GeometryNormalTexture);
1578 aShaderProgram->SetSampler (theGlContext,
1579 "uGeometryTexCrdTexture", OpenGl_RT_GeometryTexCrdTexture);
1580 aShaderProgram->SetSampler (theGlContext,
1581 "uGeometryTriangTexture", OpenGl_RT_GeometryTriangTexture);
1582 aShaderProgram->SetSampler (theGlContext,
1583 "uSceneTransformTexture", OpenGl_RT_SceneTransformTexture);
1584 aShaderProgram->SetSampler (theGlContext,
1585 "uEnvironmentMapTexture", OpenGl_RT_EnvironmentMapTexture);
1586 aShaderProgram->SetSampler (theGlContext,
1587 "uRaytraceMaterialTexture", OpenGl_RT_RaytraceMaterialTexture);
1588 aShaderProgram->SetSampler (theGlContext,
1589 "uRaytraceLightSrcTexture", OpenGl_RT_RaytraceLightSrcTexture);
1593 aShaderProgram->SetSampler (theGlContext,
1594 "uFSAAInputTexture", OpenGl_RT_FsaaInputTexture);
1598 aShaderProgram->SetSampler (theGlContext,
1599 "uAccumTexture", OpenGl_RT_PrevAccumTexture);
1602 myUniformLocations[anIndex][OpenGl_RT_aPosition] =
1603 aShaderProgram->GetAttributeLocation (theGlContext, "occVertex");
1605 myUniformLocations[anIndex][OpenGl_RT_uOriginLB] =
1606 aShaderProgram->GetUniformLocation (theGlContext, "uOriginLB");
1607 myUniformLocations[anIndex][OpenGl_RT_uOriginRB] =
1608 aShaderProgram->GetUniformLocation (theGlContext, "uOriginRB");
1609 myUniformLocations[anIndex][OpenGl_RT_uOriginLT] =
1610 aShaderProgram->GetUniformLocation (theGlContext, "uOriginLT");
1611 myUniformLocations[anIndex][OpenGl_RT_uOriginRT] =
1612 aShaderProgram->GetUniformLocation (theGlContext, "uOriginRT");
1613 myUniformLocations[anIndex][OpenGl_RT_uDirectLB] =
1614 aShaderProgram->GetUniformLocation (theGlContext, "uDirectLB");
1615 myUniformLocations[anIndex][OpenGl_RT_uDirectRB] =
1616 aShaderProgram->GetUniformLocation (theGlContext, "uDirectRB");
1617 myUniformLocations[anIndex][OpenGl_RT_uDirectLT] =
1618 aShaderProgram->GetUniformLocation (theGlContext, "uDirectLT");
1619 myUniformLocations[anIndex][OpenGl_RT_uDirectRT] =
1620 aShaderProgram->GetUniformLocation (theGlContext, "uDirectRT");
1621 myUniformLocations[anIndex][OpenGl_RT_uViewPrMat] =
1622 aShaderProgram->GetUniformLocation (theGlContext, "uViewMat");
1623 myUniformLocations[anIndex][OpenGl_RT_uUnviewMat] =
1624 aShaderProgram->GetUniformLocation (theGlContext, "uUnviewMat");
1626 myUniformLocations[anIndex][OpenGl_RT_uSceneRad] =
1627 aShaderProgram->GetUniformLocation (theGlContext, "uSceneRadius");
1628 myUniformLocations[anIndex][OpenGl_RT_uSceneEps] =
1629 aShaderProgram->GetUniformLocation (theGlContext, "uSceneEpsilon");
1630 myUniformLocations[anIndex][OpenGl_RT_uLightCount] =
1631 aShaderProgram->GetUniformLocation (theGlContext, "uLightCount");
1632 myUniformLocations[anIndex][OpenGl_RT_uLightAmbnt] =
1633 aShaderProgram->GetUniformLocation (theGlContext, "uGlobalAmbient");
1635 myUniformLocations[anIndex][OpenGl_RT_uOffsetX] =
1636 aShaderProgram->GetUniformLocation (theGlContext, "uOffsetX");
1637 myUniformLocations[anIndex][OpenGl_RT_uOffsetY] =
1638 aShaderProgram->GetUniformLocation (theGlContext, "uOffsetY");
1639 myUniformLocations[anIndex][OpenGl_RT_uSamples] =
1640 aShaderProgram->GetUniformLocation (theGlContext, "uSamples");
1642 myUniformLocations[anIndex][OpenGl_RT_uTexSamplersArray] =
1643 aShaderProgram->GetUniformLocation (theGlContext, "uTextureSamplers");
1645 myUniformLocations[anIndex][OpenGl_RT_uShadowsEnabled] =
1646 aShaderProgram->GetUniformLocation (theGlContext, "uShadowsEnabled");
1647 myUniformLocations[anIndex][OpenGl_RT_uReflectEnabled] =
1648 aShaderProgram->GetUniformLocation (theGlContext, "uReflectEnabled");
1649 myUniformLocations[anIndex][OpenGl_RT_uSphereMapEnabled] =
1650 aShaderProgram->GetUniformLocation (theGlContext, "uSphereMapEnabled");
1651 myUniformLocations[anIndex][OpenGl_RT_uSphereMapForBack] =
1652 aShaderProgram->GetUniformLocation (theGlContext, "uSphereMapForBack");
1653 myUniformLocations[anIndex][OpenGl_RT_uBlockedRngEnabled] =
1654 aShaderProgram->GetUniformLocation (theGlContext, "uBlockedRngEnabled");
1656 myUniformLocations[anIndex][OpenGl_RT_uWinSizeX] =
1657 aShaderProgram->GetUniformLocation (theGlContext, "uWinSizeX");
1658 myUniformLocations[anIndex][OpenGl_RT_uWinSizeY] =
1659 aShaderProgram->GetUniformLocation (theGlContext, "uWinSizeY");
1661 myUniformLocations[anIndex][OpenGl_RT_uAccumSamples] =
1662 aShaderProgram->GetUniformLocation (theGlContext, "uAccumSamples");
1663 myUniformLocations[anIndex][OpenGl_RT_uFrameRndSeed] =
1664 aShaderProgram->GetUniformLocation (theGlContext, "uFrameRndSeed");
1666 myUniformLocations[anIndex][OpenGl_RT_uRenderImage] =
1667 aShaderProgram->GetUniformLocation (theGlContext, "uRenderImage");
1668 myUniformLocations[anIndex][OpenGl_RT_uTilesImage] =
1669 aShaderProgram->GetUniformLocation (theGlContext, "uTilesImage");
1670 myUniformLocations[anIndex][OpenGl_RT_uOffsetImage] =
1671 aShaderProgram->GetUniformLocation (theGlContext, "uOffsetImage");
1672 myUniformLocations[anIndex][OpenGl_RT_uTileSize] =
1673 aShaderProgram->GetUniformLocation (theGlContext, "uTileSize");
1674 myUniformLocations[anIndex][OpenGl_RT_uVarianceScaleFactor] =
1675 aShaderProgram->GetUniformLocation (theGlContext, "uVarianceScaleFactor");
1677 myUniformLocations[anIndex][OpenGl_RT_uBackColorTop] =
1678 aShaderProgram->GetUniformLocation (theGlContext, "uBackColorTop");
1679 myUniformLocations[anIndex][OpenGl_RT_uBackColorBot] =
1680 aShaderProgram->GetUniformLocation (theGlContext, "uBackColorBot");
1682 myUniformLocations[anIndex][OpenGl_RT_uMaxRadiance] =
1683 aShaderProgram->GetUniformLocation (theGlContext, "uMaxRadiance");
1686 theGlContext->BindProgram (myOutImageProgram);
1688 myOutImageProgram->SetSampler (theGlContext,
1689 "uInputTexture", OpenGl_RT_PrevAccumTexture);
1691 myOutImageProgram->SetSampler (theGlContext,
1692 "uDepthTexture", OpenGl_RT_RaytraceDepthTexture);
1694 theGlContext->BindProgram (NULL);
1697 if (myRaytraceInitStatus != OpenGl_RT_NONE)
1699 return myRaytraceInitStatus == OpenGl_RT_INIT;
1702 const GLfloat aVertices[] = { -1.f, -1.f, 0.f,
1709 myRaytraceScreenQuad.Init (theGlContext, 3, 6, aVertices);
1711 myRaytraceInitStatus = OpenGl_RT_INIT; // initialized in normal way
1713 return Standard_True;
1716 // =======================================================================
1717 // function : nullifyResource
1718 // purpose : Releases OpenGL resource
1719 // =======================================================================
1721 inline void nullifyResource (const Handle(OpenGl_Context)& theGlContext, Handle(T)& theResource)
1723 if (!theResource.IsNull())
1725 theResource->Release (theGlContext.get());
1726 theResource.Nullify();
1730 // =======================================================================
1731 // function : releaseRaytraceResources
1732 // purpose : Releases OpenGL/GLSL shader programs
1733 // =======================================================================
1734 void OpenGl_View::releaseRaytraceResources (const Handle(OpenGl_Context)& theGlContext, const Standard_Boolean theToRebuild)
1736 // release shader resources
1737 nullifyResource (theGlContext, myRaytraceShader);
1738 nullifyResource (theGlContext, myPostFSAAShader);
1740 nullifyResource (theGlContext, myRaytraceProgram);
1741 nullifyResource (theGlContext, myPostFSAAProgram);
1742 nullifyResource (theGlContext, myOutImageProgram);
1744 if (!theToRebuild) // complete release
1746 myRaytraceFBO1[0]->Release (theGlContext.get());
1747 myRaytraceFBO1[1]->Release (theGlContext.get());
1748 myRaytraceFBO2[0]->Release (theGlContext.get());
1749 myRaytraceFBO2[1]->Release (theGlContext.get());
1751 nullifyResource (theGlContext, myRaytraceOutputTexture[0]);
1752 nullifyResource (theGlContext, myRaytraceOutputTexture[1]);
1754 nullifyResource (theGlContext, myRaytraceTileOffsetsTexture[0]);
1755 nullifyResource (theGlContext, myRaytraceTileOffsetsTexture[1]);
1756 nullifyResource (theGlContext, myRaytraceVisualErrorTexture[0]);
1757 nullifyResource (theGlContext, myRaytraceVisualErrorTexture[1]);
1758 nullifyResource (theGlContext, myRaytraceTileSamplesTexture[0]);
1759 nullifyResource (theGlContext, myRaytraceTileSamplesTexture[1]);
1761 nullifyResource (theGlContext, mySceneNodeInfoTexture);
1762 nullifyResource (theGlContext, mySceneMinPointTexture);
1763 nullifyResource (theGlContext, mySceneMaxPointTexture);
1765 nullifyResource (theGlContext, myGeometryVertexTexture);
1766 nullifyResource (theGlContext, myGeometryNormalTexture);
1767 nullifyResource (theGlContext, myGeometryTexCrdTexture);
1768 nullifyResource (theGlContext, myGeometryTriangTexture);
1769 nullifyResource (theGlContext, mySceneTransformTexture);
1771 nullifyResource (theGlContext, myRaytraceLightSrcTexture);
1772 nullifyResource (theGlContext, myRaytraceMaterialTexture);
1774 myRaytraceGeometry.ReleaseResources (theGlContext);
1776 if (myRaytraceScreenQuad.IsValid ())
1778 myRaytraceScreenQuad.Release (theGlContext.get());
1783 // =======================================================================
1784 // function : updateRaytraceBuffers
1785 // purpose : Updates auxiliary OpenGL frame buffers.
1786 // =======================================================================
1787 Standard_Boolean OpenGl_View::updateRaytraceBuffers (const Standard_Integer theSizeX,
1788 const Standard_Integer theSizeY,
1789 const Handle(OpenGl_Context)& theGlContext)
1791 // Auxiliary buffers are not used
1792 if (!myRaytraceParameters.GlobalIllumination && !myRenderParams.IsAntialiasingEnabled)
1794 myRaytraceFBO1[0]->Release (theGlContext.operator->());
1795 myRaytraceFBO2[0]->Release (theGlContext.operator->());
1796 myRaytraceFBO1[1]->Release (theGlContext.operator->());
1797 myRaytraceFBO2[1]->Release (theGlContext.operator->());
1799 return Standard_True;
1802 if (myRaytraceParameters.AdaptiveScreenSampling)
1804 Graphic3d_Vec2i aMaxViewport = myTileSampler.OffsetTilesViewportMax().cwiseMax (Graphic3d_Vec2i (theSizeX, theSizeY));
1805 myRaytraceFBO1[0]->InitLazy (theGlContext, aMaxViewport.x(), aMaxViewport.y(), GL_RGBA32F, myFboDepthFormat);
1806 myRaytraceFBO2[0]->InitLazy (theGlContext, aMaxViewport.x(), aMaxViewport.y(), GL_RGBA32F, myFboDepthFormat);
1807 if (myRaytraceFBO1[1]->IsValid()) // second FBO not needed
1809 myRaytraceFBO1[1]->Release (theGlContext.operator->());
1810 myRaytraceFBO2[1]->Release (theGlContext.operator->());
1814 for (int aViewIter = 0; aViewIter < 2; ++aViewIter)
1816 if (myRaytraceTileOffsetsTexture[aViewIter].IsNull())
1818 myRaytraceOutputTexture[aViewIter] = new OpenGl_Texture();
1819 myRaytraceVisualErrorTexture[aViewIter] = new OpenGl_Texture();
1820 myRaytraceTileSamplesTexture[aViewIter] = new OpenGl_Texture();
1821 myRaytraceTileOffsetsTexture[aViewIter] = new OpenGl_Texture();
1825 && myCamera->ProjectionType() != Graphic3d_Camera::Projection_Stereo)
1827 myRaytraceFBO1[1]->Release (theGlContext.operator->());
1828 myRaytraceFBO2[1]->Release (theGlContext.operator->());
1829 myRaytraceOutputTexture[1]->Release (theGlContext.operator->());
1830 myRaytraceVisualErrorTexture[1]->Release (theGlContext.operator->());
1831 myRaytraceTileOffsetsTexture[1]->Release (theGlContext.operator->());
1835 if (myRaytraceParameters.AdaptiveScreenSampling)
1837 if (myRaytraceOutputTexture[aViewIter]->SizeX() / 3 == theSizeX
1838 && myRaytraceOutputTexture[aViewIter]->SizeY() / 2 == theSizeY
1839 && myRaytraceVisualErrorTexture[aViewIter]->SizeX() == myTileSampler.NbTilesX()
1840 && myRaytraceVisualErrorTexture[aViewIter]->SizeY() == myTileSampler.NbTilesY())
1842 if (myRaytraceParameters.AdaptiveScreenSamplingAtomic)
1844 continue; // offsets texture is dynamically resized
1846 else if (myRaytraceTileSamplesTexture[aViewIter]->SizeX() == myTileSampler.NbTilesX()
1847 && myRaytraceTileSamplesTexture[aViewIter]->SizeY() == myTileSampler.NbTilesY())
1855 // Due to limitations of OpenGL image load-store extension
1856 // atomic operations are supported only for single-channel
1857 // images, so we define GL_R32F image. It is used as array
1858 // of 6D floating point vectors:
1859 // 0 - R color channel
1860 // 1 - G color channel
1861 // 2 - B color channel
1862 // 3 - hit time transformed into OpenGL NDC space
1863 // 4 - luminance accumulated for odd samples only
1864 myRaytraceOutputTexture[aViewIter]->InitRectangle (theGlContext, theSizeX * 3, theSizeY * 2, OpenGl_TextureFormat::Create<GLfloat, 1>());
1866 // workaround for some NVIDIA drivers
1867 myRaytraceVisualErrorTexture[aViewIter]->Release (theGlContext.operator->());
1868 myRaytraceTileSamplesTexture[aViewIter]->Release (theGlContext.operator->());
1869 myRaytraceVisualErrorTexture[aViewIter]->Init (theGlContext, GL_R32I, GL_RED_INTEGER, GL_INT,
1870 myTileSampler.NbTilesX(), myTileSampler.NbTilesY(), Graphic3d_TOT_2D);
1871 if (!myRaytraceParameters.AdaptiveScreenSamplingAtomic)
1873 myRaytraceTileSamplesTexture[aViewIter]->Init (theGlContext, GL_R32I, GL_RED_INTEGER, GL_INT,
1874 myTileSampler.NbTilesX(), myTileSampler.NbTilesY(), Graphic3d_TOT_2D);
1877 else // non-adaptive mode
1879 if (myRaytraceFBO1[aViewIter]->GetSizeX() != theSizeX
1880 || myRaytraceFBO1[aViewIter]->GetSizeY() != theSizeY)
1882 myAccumFrames = 0; // accumulation should be restarted
1885 myRaytraceFBO1[aViewIter]->InitLazy (theGlContext, theSizeX, theSizeY, GL_RGBA32F, myFboDepthFormat);
1886 myRaytraceFBO2[aViewIter]->InitLazy (theGlContext, theSizeX, theSizeY, GL_RGBA32F, myFboDepthFormat);
1889 return Standard_True;
1892 // =======================================================================
1893 // function : updateCamera
1894 // purpose : Generates viewing rays for corners of screen quad
1895 // =======================================================================
1896 void OpenGl_View::updateCamera (const OpenGl_Mat4& theOrientation,
1897 const OpenGl_Mat4& theViewMapping,
1898 OpenGl_Vec3* theOrigins,
1899 OpenGl_Vec3* theDirects,
1900 OpenGl_Mat4& theViewPr,
1901 OpenGl_Mat4& theUnview)
1903 // compute view-projection matrix
1904 theViewPr = theViewMapping * theOrientation;
1906 // compute inverse view-projection matrix
1907 theViewPr.Inverted (theUnview);
1909 Standard_Integer aOriginIndex = 0;
1910 Standard_Integer aDirectIndex = 0;
1912 for (Standard_Integer aY = -1; aY <= 1; aY += 2)
1914 for (Standard_Integer aX = -1; aX <= 1; aX += 2)
1916 OpenGl_Vec4 aOrigin (GLfloat(aX),
1921 aOrigin = theUnview * aOrigin;
1923 aOrigin.x() = aOrigin.x() / aOrigin.w();
1924 aOrigin.y() = aOrigin.y() / aOrigin.w();
1925 aOrigin.z() = aOrigin.z() / aOrigin.w();
1927 OpenGl_Vec4 aDirect (GLfloat(aX),
1932 aDirect = theUnview * aDirect;
1934 aDirect.x() = aDirect.x() / aDirect.w();
1935 aDirect.y() = aDirect.y() / aDirect.w();
1936 aDirect.z() = aDirect.z() / aDirect.w();
1938 aDirect = aDirect - aOrigin;
1940 theOrigins[aOriginIndex++] = OpenGl_Vec3 (static_cast<GLfloat> (aOrigin.x()),
1941 static_cast<GLfloat> (aOrigin.y()),
1942 static_cast<GLfloat> (aOrigin.z()));
1944 theDirects[aDirectIndex++] = OpenGl_Vec3 (static_cast<GLfloat> (aDirect.x()),
1945 static_cast<GLfloat> (aDirect.y()),
1946 static_cast<GLfloat> (aDirect.z()));
1951 // =======================================================================
1952 // function : updatePerspCameraPT
1953 // purpose : Generates viewing rays (path tracing, perspective camera)
1954 // =======================================================================
1955 void OpenGl_View::updatePerspCameraPT (const OpenGl_Mat4& theOrientation,
1956 const OpenGl_Mat4& theViewMapping,
1957 Graphic3d_Camera::Projection theProjection,
1958 OpenGl_Mat4& theViewPr,
1959 OpenGl_Mat4& theUnview,
1960 const int theWinSizeX,
1961 const int theWinSizeY)
1963 // compute view-projection matrix
1964 theViewPr = theViewMapping * theOrientation;
1966 // compute inverse view-projection matrix
1967 theViewPr.Inverted(theUnview);
1969 // get camera stereo params
1970 float anIOD = myCamera->GetIODType() == Graphic3d_Camera::IODType_Relative
1971 ? static_cast<float> (myCamera->IOD() * myCamera->Distance())
1972 : static_cast<float> (myCamera->IOD());
1974 float aZFocus = myCamera->ZFocusType() == Graphic3d_Camera::FocusType_Relative
1975 ? static_cast<float> (myCamera->ZFocus() * myCamera->Distance())
1976 : static_cast<float> (myCamera->ZFocus());
1978 // get camera view vectors
1979 const gp_Pnt anOrig = myCamera->Eye();
1981 myEyeOrig = OpenGl_Vec3 (static_cast<float> (anOrig.X()),
1982 static_cast<float> (anOrig.Y()),
1983 static_cast<float> (anOrig.Z()));
1985 const gp_Dir aView = myCamera->Direction();
1987 OpenGl_Vec3 anEyeViewMono = OpenGl_Vec3 (static_cast<float> (aView.X()),
1988 static_cast<float> (aView.Y()),
1989 static_cast<float> (aView.Z()));
1991 const gp_Dir anUp = myCamera->Up();
1993 myEyeVert = OpenGl_Vec3 (static_cast<float> (anUp.X()),
1994 static_cast<float> (anUp.Y()),
1995 static_cast<float> (anUp.Z()));
1997 myEyeSide = OpenGl_Vec3::Cross (anEyeViewMono, myEyeVert);
1999 const double aScaleY = tan (myCamera->FOVy() / 360 * M_PI);
2000 const double aScaleX = theWinSizeX * aScaleY / theWinSizeY;
2002 myEyeSize = OpenGl_Vec2 (static_cast<float> (aScaleX),
2003 static_cast<float> (aScaleY));
2005 if (theProjection == Graphic3d_Camera::Projection_Perspective)
2007 myEyeView = anEyeViewMono;
2009 else // stereo camera
2011 // compute z-focus point
2012 OpenGl_Vec3 aZFocusPoint = myEyeOrig + anEyeViewMono * aZFocus;
2014 // compute stereo camera shift
2015 float aDx = theProjection == Graphic3d_Camera::Projection_MonoRightEye ? 0.5f * anIOD : -0.5f * anIOD;
2016 myEyeOrig += myEyeSide.Normalized() * aDx;
2018 // estimate new camera direction vector and correct its length
2019 myEyeView = (aZFocusPoint - myEyeOrig).Normalized();
2020 myEyeView *= 1.f / anEyeViewMono.Dot (myEyeView);
2024 // =======================================================================
2025 // function : uploadRaytraceData
2026 // purpose : Uploads ray-trace data to the GPU
2027 // =======================================================================
2028 Standard_Boolean OpenGl_View::uploadRaytraceData (const Handle(OpenGl_Context)& theGlContext)
2030 if (!theGlContext->IsGlGreaterEqual (3, 1))
2032 #ifdef RAY_TRACE_PRINT_INFO
2033 std::cout << "Error: OpenGL version is less than 3.1" << std::endl;
2035 return Standard_False;
2038 myAccumFrames = 0; // accumulation should be restarted
2040 /////////////////////////////////////////////////////////////////////////////
2041 // Prepare OpenGL textures
2043 if (theGlContext->arbTexBindless != NULL)
2045 // If OpenGL driver supports bindless textures we need
2046 // to get unique 64- bit handles for using on the GPU
2047 if (!myRaytraceGeometry.UpdateTextureHandles (theGlContext))
2049 #ifdef RAY_TRACE_PRINT_INFO
2050 std::cout << "Error: Failed to get OpenGL texture handles" << std::endl;
2052 return Standard_False;
2056 /////////////////////////////////////////////////////////////////////////////
2057 // Create OpenGL BVH buffers
2059 if (mySceneNodeInfoTexture.IsNull()) // create scene BVH buffers
2061 mySceneNodeInfoTexture = new OpenGl_TextureBufferArb;
2062 mySceneMinPointTexture = new OpenGl_TextureBufferArb;
2063 mySceneMaxPointTexture = new OpenGl_TextureBufferArb;
2064 mySceneTransformTexture = new OpenGl_TextureBufferArb;
2066 if (!mySceneNodeInfoTexture->Create (theGlContext)
2067 || !mySceneMinPointTexture->Create (theGlContext)
2068 || !mySceneMaxPointTexture->Create (theGlContext)
2069 || !mySceneTransformTexture->Create (theGlContext))
2071 #ifdef RAY_TRACE_PRINT_INFO
2072 std::cout << "Error: Failed to create scene BVH buffers" << std::endl;
2074 return Standard_False;
2078 if (myGeometryVertexTexture.IsNull()) // create geometry buffers
2080 myGeometryVertexTexture = new OpenGl_TextureBufferArb;
2081 myGeometryNormalTexture = new OpenGl_TextureBufferArb;
2082 myGeometryTexCrdTexture = new OpenGl_TextureBufferArb;
2083 myGeometryTriangTexture = new OpenGl_TextureBufferArb;
2085 if (!myGeometryVertexTexture->Create (theGlContext)
2086 || !myGeometryNormalTexture->Create (theGlContext)
2087 || !myGeometryTexCrdTexture->Create (theGlContext)
2088 || !myGeometryTriangTexture->Create (theGlContext))
2090 #ifdef RAY_TRACE_PRINT_INFO
2091 std::cout << "Error: Failed to create buffers for triangulation data" << std::endl;
2093 return Standard_False;
2097 if (myRaytraceMaterialTexture.IsNull()) // create material buffer
2099 myRaytraceMaterialTexture = new OpenGl_TextureBufferArb;
2101 if (!myRaytraceMaterialTexture->Create (theGlContext))
2103 #ifdef RAY_TRACE_PRINT_INFO
2104 std::cout << "Error: Failed to create buffers for material data" << std::endl;
2106 return Standard_False;
2110 /////////////////////////////////////////////////////////////////////////////
2111 // Write transform buffer
2113 BVH_Mat4f* aNodeTransforms = new BVH_Mat4f[myRaytraceGeometry.Size()];
2115 bool aResult = true;
2117 for (Standard_Integer anElemIndex = 0; anElemIndex < myRaytraceGeometry.Size(); ++anElemIndex)
2119 OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
2120 myRaytraceGeometry.Objects().ChangeValue (anElemIndex).operator->());
2122 const BVH_Transform<Standard_ShortReal, 4>* aTransform = dynamic_cast<const BVH_Transform<Standard_ShortReal, 4>* > (aTriangleSet->Properties().get());
2123 Standard_ASSERT_RETURN (aTransform != NULL,
2124 "OpenGl_TriangleSet does not contain transform", Standard_False);
2126 aNodeTransforms[anElemIndex] = aTransform->Inversed();
2129 aResult &= mySceneTransformTexture->Init (theGlContext, 4,
2130 myRaytraceGeometry.Size() * 4, reinterpret_cast<const GLfloat*> (aNodeTransforms));
2132 delete [] aNodeTransforms;
2134 /////////////////////////////////////////////////////////////////////////////
2135 // Write geometry and bottom-level BVH buffers
2137 Standard_Size aTotalVerticesNb = 0;
2138 Standard_Size aTotalElementsNb = 0;
2139 Standard_Size aTotalBVHNodesNb = 0;
2141 for (Standard_Integer anElemIndex = 0; anElemIndex < myRaytraceGeometry.Size(); ++anElemIndex)
2143 OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
2144 myRaytraceGeometry.Objects().ChangeValue (anElemIndex).operator->());
2146 Standard_ASSERT_RETURN (aTriangleSet != NULL,
2147 "Error: Failed to get triangulation of OpenGL element", Standard_False);
2149 aTotalVerticesNb += aTriangleSet->Vertices.size();
2150 aTotalElementsNb += aTriangleSet->Elements.size();
2152 Standard_ASSERT_RETURN (!aTriangleSet->QuadBVH().IsNull(),
2153 "Error: Failed to get bottom-level BVH of OpenGL element", Standard_False);
2155 aTotalBVHNodesNb += aTriangleSet->QuadBVH()->NodeInfoBuffer().size();
2158 aTotalBVHNodesNb += myRaytraceGeometry.QuadBVH()->NodeInfoBuffer().size();
2160 if (aTotalBVHNodesNb != 0)
2162 aResult &= mySceneNodeInfoTexture->Init (
2163 theGlContext, 4, GLsizei (aTotalBVHNodesNb), static_cast<const GLuint*> (NULL));
2164 aResult &= mySceneMinPointTexture->Init (
2165 theGlContext, 3, GLsizei (aTotalBVHNodesNb), static_cast<const GLfloat*> (NULL));
2166 aResult &= mySceneMaxPointTexture->Init (
2167 theGlContext, 3, GLsizei (aTotalBVHNodesNb), static_cast<const GLfloat*> (NULL));
2172 #ifdef RAY_TRACE_PRINT_INFO
2173 std::cout << "Error: Failed to upload buffers for bottom-level scene BVH" << std::endl;
2175 return Standard_False;
2178 if (aTotalElementsNb != 0)
2180 aResult &= myGeometryTriangTexture->Init (
2181 theGlContext, 4, GLsizei (aTotalElementsNb), static_cast<const GLuint*> (NULL));
2184 if (aTotalVerticesNb != 0)
2186 aResult &= myGeometryVertexTexture->Init (
2187 theGlContext, 3, GLsizei (aTotalVerticesNb), static_cast<const GLfloat*> (NULL));
2188 aResult &= myGeometryNormalTexture->Init (
2189 theGlContext, 3, GLsizei (aTotalVerticesNb), static_cast<const GLfloat*> (NULL));
2190 aResult &= myGeometryTexCrdTexture->Init (
2191 theGlContext, 2, GLsizei (aTotalVerticesNb), static_cast<const GLfloat*> (NULL));
2196 #ifdef RAY_TRACE_PRINT_INFO
2197 std::cout << "Error: Failed to upload buffers for scene geometry" << std::endl;
2199 return Standard_False;
2202 const QuadBvhHandle& aBVH = myRaytraceGeometry.QuadBVH();
2204 if (aBVH->Length() > 0)
2206 aResult &= mySceneNodeInfoTexture->SubData (theGlContext, 0, aBVH->Length(),
2207 reinterpret_cast<const GLuint*> (&aBVH->NodeInfoBuffer().front()));
2208 aResult &= mySceneMinPointTexture->SubData (theGlContext, 0, aBVH->Length(),
2209 reinterpret_cast<const GLfloat*> (&aBVH->MinPointBuffer().front()));
2210 aResult &= mySceneMaxPointTexture->SubData (theGlContext, 0, aBVH->Length(),
2211 reinterpret_cast<const GLfloat*> (&aBVH->MaxPointBuffer().front()));
2214 for (Standard_Integer aNodeIdx = 0; aNodeIdx < aBVH->Length(); ++aNodeIdx)
2216 if (!aBVH->IsOuter (aNodeIdx))
2219 OpenGl_TriangleSet* aTriangleSet = myRaytraceGeometry.TriangleSet (aNodeIdx);
2221 Standard_ASSERT_RETURN (aTriangleSet != NULL,
2222 "Error: Failed to get triangulation of OpenGL element", Standard_False);
2224 Standard_Integer aBVHOffset = myRaytraceGeometry.AccelerationOffset (aNodeIdx);
2226 Standard_ASSERT_RETURN (aBVHOffset != OpenGl_RaytraceGeometry::INVALID_OFFSET,
2227 "Error: Failed to get offset for bottom-level BVH", Standard_False);
2229 const Standard_Integer aBvhBuffersSize = aTriangleSet->QuadBVH()->Length();
2231 if (aBvhBuffersSize != 0)
2233 aResult &= mySceneNodeInfoTexture->SubData (theGlContext, aBVHOffset, aBvhBuffersSize,
2234 reinterpret_cast<const GLuint*> (&aTriangleSet->QuadBVH()->NodeInfoBuffer().front()));
2235 aResult &= mySceneMinPointTexture->SubData (theGlContext, aBVHOffset, aBvhBuffersSize,
2236 reinterpret_cast<const GLfloat*> (&aTriangleSet->QuadBVH()->MinPointBuffer().front()));
2237 aResult &= mySceneMaxPointTexture->SubData (theGlContext, aBVHOffset, aBvhBuffersSize,
2238 reinterpret_cast<const GLfloat*> (&aTriangleSet->QuadBVH()->MaxPointBuffer().front()));
2242 #ifdef RAY_TRACE_PRINT_INFO
2243 std::cout << "Error: Failed to upload buffers for bottom-level scene BVHs" << std::endl;
2245 return Standard_False;
2249 const Standard_Integer aVerticesOffset = myRaytraceGeometry.VerticesOffset (aNodeIdx);
2251 Standard_ASSERT_RETURN (aVerticesOffset != OpenGl_RaytraceGeometry::INVALID_OFFSET,
2252 "Error: Failed to get offset for triangulation vertices of OpenGL element", Standard_False);
2254 if (!aTriangleSet->Vertices.empty())
2256 aResult &= myGeometryNormalTexture->SubData (theGlContext, aVerticesOffset,
2257 GLsizei (aTriangleSet->Normals.size()), reinterpret_cast<const GLfloat*> (&aTriangleSet->Normals.front()));
2258 aResult &= myGeometryTexCrdTexture->SubData (theGlContext, aVerticesOffset,
2259 GLsizei (aTriangleSet->TexCrds.size()), reinterpret_cast<const GLfloat*> (&aTriangleSet->TexCrds.front()));
2260 aResult &= myGeometryVertexTexture->SubData (theGlContext, aVerticesOffset,
2261 GLsizei (aTriangleSet->Vertices.size()), reinterpret_cast<const GLfloat*> (&aTriangleSet->Vertices.front()));
2264 const Standard_Integer anElementsOffset = myRaytraceGeometry.ElementsOffset (aNodeIdx);
2266 Standard_ASSERT_RETURN (anElementsOffset != OpenGl_RaytraceGeometry::INVALID_OFFSET,
2267 "Error: Failed to get offset for triangulation elements of OpenGL element", Standard_False);
2269 if (!aTriangleSet->Elements.empty())
2271 aResult &= myGeometryTriangTexture->SubData (theGlContext, anElementsOffset, GLsizei (aTriangleSet->Elements.size()),
2272 reinterpret_cast<const GLuint*> (&aTriangleSet->Elements.front()));
2277 #ifdef RAY_TRACE_PRINT_INFO
2278 std::cout << "Error: Failed to upload triangulation buffers for OpenGL element" << std::endl;
2280 return Standard_False;
2284 /////////////////////////////////////////////////////////////////////////////
2285 // Write material buffer
2287 if (myRaytraceGeometry.Materials.size() != 0)
2289 aResult &= myRaytraceMaterialTexture->Init (theGlContext, 4,
2290 GLsizei (myRaytraceGeometry.Materials.size() * 19), myRaytraceGeometry.Materials.front().Packed());
2294 #ifdef RAY_TRACE_PRINT_INFO
2295 std::cout << "Error: Failed to upload material buffer" << std::endl;
2297 return Standard_False;
2301 myIsRaytraceDataValid = myRaytraceGeometry.Objects().Size() != 0;
2303 #ifdef RAY_TRACE_PRINT_INFO
2305 Standard_ShortReal aMemTrgUsed = 0.f;
2306 Standard_ShortReal aMemBvhUsed = 0.f;
2308 for (Standard_Integer anElemIdx = 0; anElemIdx < myRaytraceGeometry.Size(); ++anElemIdx)
2310 OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (myRaytraceGeometry.Objects()(anElemIdx).get());
2312 aMemTrgUsed += static_cast<Standard_ShortReal> (
2313 aTriangleSet->Vertices.size() * sizeof (BVH_Vec3f));
2314 aMemTrgUsed += static_cast<Standard_ShortReal> (
2315 aTriangleSet->Normals.size() * sizeof (BVH_Vec3f));
2316 aMemTrgUsed += static_cast<Standard_ShortReal> (
2317 aTriangleSet->TexCrds.size() * sizeof (BVH_Vec2f));
2318 aMemTrgUsed += static_cast<Standard_ShortReal> (
2319 aTriangleSet->Elements.size() * sizeof (BVH_Vec4i));
2321 aMemBvhUsed += static_cast<Standard_ShortReal> (
2322 aTriangleSet->QuadBVH()->NodeInfoBuffer().size() * sizeof (BVH_Vec4i));
2323 aMemBvhUsed += static_cast<Standard_ShortReal> (
2324 aTriangleSet->QuadBVH()->MinPointBuffer().size() * sizeof (BVH_Vec3f));
2325 aMemBvhUsed += static_cast<Standard_ShortReal> (
2326 aTriangleSet->QuadBVH()->MaxPointBuffer().size() * sizeof (BVH_Vec3f));
2329 aMemBvhUsed += static_cast<Standard_ShortReal> (
2330 myRaytraceGeometry.QuadBVH()->NodeInfoBuffer().size() * sizeof (BVH_Vec4i));
2331 aMemBvhUsed += static_cast<Standard_ShortReal> (
2332 myRaytraceGeometry.QuadBVH()->MinPointBuffer().size() * sizeof (BVH_Vec3f));
2333 aMemBvhUsed += static_cast<Standard_ShortReal> (
2334 myRaytraceGeometry.QuadBVH()->MaxPointBuffer().size() * sizeof (BVH_Vec3f));
2336 std::cout << "GPU Memory Used (Mb):\n"
2337 << "\tFor mesh: " << aMemTrgUsed / 1048576 << "\n"
2338 << "\tFor BVHs: " << aMemBvhUsed / 1048576 << "\n";
2345 // =======================================================================
2346 // function : updateRaytraceLightSources
2347 // purpose : Updates 3D scene light sources for ray-tracing
2348 // =======================================================================
2349 Standard_Boolean OpenGl_View::updateRaytraceLightSources (const OpenGl_Mat4& theInvModelView, const Handle(OpenGl_Context)& theGlContext)
2351 std::vector<Handle(Graphic3d_CLight)> aLightSources;
2352 myRaytraceGeometry.Ambient = BVH_Vec4f (0.f, 0.f, 0.f, 0.f);
2353 if (myShadingModel != Graphic3d_TOSM_UNLIT
2354 && !myLights.IsNull())
2356 const Graphic3d_Vec4& anAmbient = myLights->AmbientColor();
2357 myRaytraceGeometry.Ambient = BVH_Vec4f (anAmbient.r(), anAmbient.g(), anAmbient.b(), 0.0f);
2359 // move positional light sources at the front of the list
2360 aLightSources.reserve (myLights->Extent());
2361 for (Graphic3d_LightSet::Iterator aLightIter (myLights, Graphic3d_LightSet::IterationFilter_ExcludeDisabledAndAmbient);
2362 aLightIter.More(); aLightIter.Next())
2364 const Graphic3d_CLight& aLight = *aLightIter.Value();
2365 if (aLight.Type() != Graphic3d_TOLS_DIRECTIONAL)
2367 aLightSources.push_back (aLightIter.Value());
2371 for (Graphic3d_LightSet::Iterator aLightIter (myLights, Graphic3d_LightSet::IterationFilter_ExcludeDisabledAndAmbient);
2372 aLightIter.More(); aLightIter.Next())
2374 if (aLightIter.Value()->Type() == Graphic3d_TOLS_DIRECTIONAL)
2376 aLightSources.push_back (aLightIter.Value());
2381 // get number of 'real' (not ambient) light sources
2382 const size_t aNbLights = aLightSources.size();
2383 Standard_Boolean wasUpdated = myRaytraceGeometry.Sources.size () != aNbLights;
2386 myRaytraceGeometry.Sources.resize (aNbLights);
2389 for (size_t aLightIdx = 0, aRealIdx = 0; aLightIdx < aLightSources.size(); ++aLightIdx)
2391 const Graphic3d_CLight& aLight = *aLightSources[aLightIdx];
2392 const Graphic3d_Vec4& aLightColor = aLight.PackedColor();
2393 BVH_Vec4f aEmission (aLightColor.r() * aLight.Intensity(),
2394 aLightColor.g() * aLight.Intensity(),
2395 aLightColor.b() * aLight.Intensity(),
2398 BVH_Vec4f aPosition (-aLight.PackedDirection().x(),
2399 -aLight.PackedDirection().y(),
2400 -aLight.PackedDirection().z(),
2403 if (aLight.Type() != Graphic3d_TOLS_DIRECTIONAL)
2405 aPosition = BVH_Vec4f (static_cast<float>(aLight.Position().X()),
2406 static_cast<float>(aLight.Position().Y()),
2407 static_cast<float>(aLight.Position().Z()),
2410 // store smoothing radius in W-component
2411 aEmission.w() = Max (aLight.Smoothness(), 0.f);
2415 // store cosine of smoothing angle in W-component
2416 aEmission.w() = cosf (Min (Max (aLight.Smoothness(), 0.f), static_cast<Standard_ShortReal> (M_PI / 2.0)));
2419 if (aLight.IsHeadlight())
2421 aPosition = theInvModelView * aPosition;
2424 for (int aK = 0; aK < 4; ++aK)
2426 wasUpdated |= (aEmission[aK] != myRaytraceGeometry.Sources[aRealIdx].Emission[aK])
2427 || (aPosition[aK] != myRaytraceGeometry.Sources[aRealIdx].Position[aK]);
2432 myRaytraceGeometry.Sources[aRealIdx] = OpenGl_RaytraceLight (aEmission, aPosition);
2438 if (myRaytraceLightSrcTexture.IsNull()) // create light source buffer
2440 myRaytraceLightSrcTexture = new OpenGl_TextureBufferArb;
2443 if (myRaytraceGeometry.Sources.size() != 0 && wasUpdated)
2445 const GLfloat* aDataPtr = myRaytraceGeometry.Sources.front().Packed();
2446 if (!myRaytraceLightSrcTexture->Init (theGlContext, 4, GLsizei (myRaytraceGeometry.Sources.size() * 2), aDataPtr))
2448 #ifdef RAY_TRACE_PRINT_INFO
2449 std::cout << "Error: Failed to upload light source buffer" << std::endl;
2451 return Standard_False;
2454 myAccumFrames = 0; // accumulation should be restarted
2457 return Standard_True;
2460 // =======================================================================
2461 // function : setUniformState
2462 // purpose : Sets uniform state for the given ray-tracing shader program
2463 // =======================================================================
2464 Standard_Boolean OpenGl_View::setUniformState (const Standard_Integer theProgramId,
2465 const Standard_Integer theWinSizeX,
2466 const Standard_Integer theWinSizeY,
2467 Graphic3d_Camera::Projection theProjection,
2468 const Handle(OpenGl_Context)& theGlContext)
2470 // Get projection state
2471 OpenGl_MatrixState<Standard_ShortReal>& aCntxProjectionState = theGlContext->ProjectionState;
2473 OpenGl_Mat4 aViewPrjMat;
2474 OpenGl_Mat4 anUnviewMat;
2475 OpenGl_Vec3 aOrigins[4];
2476 OpenGl_Vec3 aDirects[4];
2478 if (myCamera->IsOrthographic()
2479 || !myRenderParams.IsGlobalIlluminationEnabled)
2481 updateCamera (myCamera->OrientationMatrixF(),
2482 aCntxProjectionState.Current(),
2490 updatePerspCameraPT (myCamera->OrientationMatrixF(),
2491 aCntxProjectionState.Current(),
2499 Handle(OpenGl_ShaderProgram)& theProgram = theProgramId == 0
2501 : myPostFSAAProgram;
2503 if (theProgram.IsNull())
2505 return Standard_False;
2508 theProgram->SetUniform(theGlContext, "uEyeOrig", myEyeOrig);
2509 theProgram->SetUniform(theGlContext, "uEyeView", myEyeView);
2510 theProgram->SetUniform(theGlContext, "uEyeVert", myEyeVert);
2511 theProgram->SetUniform(theGlContext, "uEyeSide", myEyeSide);
2512 theProgram->SetUniform(theGlContext, "uEyeSize", myEyeSize);
2514 theProgram->SetUniform(theGlContext, "uApertureRadius", myRenderParams.CameraApertureRadius);
2515 theProgram->SetUniform(theGlContext, "uFocalPlaneDist", myRenderParams.CameraFocalPlaneDist);
2518 theProgram->SetUniform (theGlContext,
2519 myUniformLocations[theProgramId][OpenGl_RT_uOriginLB], aOrigins[0]);
2520 theProgram->SetUniform (theGlContext,
2521 myUniformLocations[theProgramId][OpenGl_RT_uOriginRB], aOrigins[1]);
2522 theProgram->SetUniform (theGlContext,
2523 myUniformLocations[theProgramId][OpenGl_RT_uOriginLT], aOrigins[2]);
2524 theProgram->SetUniform (theGlContext,
2525 myUniformLocations[theProgramId][OpenGl_RT_uOriginRT], aOrigins[3]);
2526 theProgram->SetUniform (theGlContext,
2527 myUniformLocations[theProgramId][OpenGl_RT_uDirectLB], aDirects[0]);
2528 theProgram->SetUniform (theGlContext,
2529 myUniformLocations[theProgramId][OpenGl_RT_uDirectRB], aDirects[1]);
2530 theProgram->SetUniform (theGlContext,
2531 myUniformLocations[theProgramId][OpenGl_RT_uDirectLT], aDirects[2]);
2532 theProgram->SetUniform (theGlContext,
2533 myUniformLocations[theProgramId][OpenGl_RT_uDirectRT], aDirects[3]);
2534 theProgram->SetUniform (theGlContext,
2535 myUniformLocations[theProgramId][OpenGl_RT_uViewPrMat], aViewPrjMat);
2536 theProgram->SetUniform (theGlContext,
2537 myUniformLocations[theProgramId][OpenGl_RT_uUnviewMat], anUnviewMat);
2539 // Set screen dimensions
2540 myRaytraceProgram->SetUniform (theGlContext,
2541 myUniformLocations[theProgramId][OpenGl_RT_uWinSizeX], theWinSizeX);
2542 myRaytraceProgram->SetUniform (theGlContext,
2543 myUniformLocations[theProgramId][OpenGl_RT_uWinSizeY], theWinSizeY);
2545 // Set 3D scene parameters
2546 theProgram->SetUniform (theGlContext,
2547 myUniformLocations[theProgramId][OpenGl_RT_uSceneRad], myRaytraceSceneRadius);
2548 theProgram->SetUniform (theGlContext,
2549 myUniformLocations[theProgramId][OpenGl_RT_uSceneEps], myRaytraceSceneEpsilon);
2551 // Set light source parameters
2552 const Standard_Integer aLightSourceBufferSize =
2553 static_cast<Standard_Integer> (myRaytraceGeometry.Sources.size());
2555 theProgram->SetUniform (theGlContext,
2556 myUniformLocations[theProgramId][OpenGl_RT_uLightCount], aLightSourceBufferSize);
2558 // Set array of 64-bit texture handles
2559 if (theGlContext->arbTexBindless != NULL && myRaytraceGeometry.HasTextures())
2561 const std::vector<GLuint64>& aTextures = myRaytraceGeometry.TextureHandles();
2563 theProgram->SetUniform (theGlContext, myUniformLocations[theProgramId][OpenGl_RT_uTexSamplersArray],
2564 static_cast<GLsizei> (aTextures.size()), reinterpret_cast<const OpenGl_Vec2u*> (&aTextures.front()));
2567 // Set background colors (only gradient background supported)
2568 if (myBackgrounds[Graphic3d_TOB_GRADIENT] != NULL
2569 && myBackgrounds[Graphic3d_TOB_GRADIENT]->IsDefined())
2571 theProgram->SetUniform (theGlContext,
2572 myUniformLocations[theProgramId][OpenGl_RT_uBackColorTop], myBackgrounds[Graphic3d_TOB_GRADIENT]->GradientColor (0));
2573 theProgram->SetUniform (theGlContext,
2574 myUniformLocations[theProgramId][OpenGl_RT_uBackColorBot], myBackgrounds[Graphic3d_TOB_GRADIENT]->GradientColor (1));
2578 const OpenGl_Vec4& aBackColor = myBgColor;
2580 theProgram->SetUniform (theGlContext,
2581 myUniformLocations[theProgramId][OpenGl_RT_uBackColorTop], aBackColor);
2582 theProgram->SetUniform (theGlContext,
2583 myUniformLocations[theProgramId][OpenGl_RT_uBackColorBot], aBackColor);
2586 // Set environment map parameters
2587 const Standard_Boolean toDisableEnvironmentMap = myTextureEnv.IsNull()
2588 || myTextureEnv->IsEmpty()
2589 || !myTextureEnv->First()->IsValid();
2591 theProgram->SetUniform (theGlContext,
2592 myUniformLocations[theProgramId][OpenGl_RT_uSphereMapEnabled], toDisableEnvironmentMap ? 0 : 1);
2594 theProgram->SetUniform (theGlContext,
2595 myUniformLocations[theProgramId][OpenGl_RT_uSphereMapForBack], myRenderParams.UseEnvironmentMapBackground ? 1 : 0);
2597 if (myRenderParams.IsGlobalIlluminationEnabled) // GI parameters
2599 theProgram->SetUniform (theGlContext,
2600 myUniformLocations[theProgramId][OpenGl_RT_uMaxRadiance], myRenderParams.RadianceClampingValue);
2602 theProgram->SetUniform (theGlContext,
2603 myUniformLocations[theProgramId][OpenGl_RT_uBlockedRngEnabled], myRenderParams.CoherentPathTracingMode ? 1 : 0);
2605 // Check whether we should restart accumulation for run-time parameters
2606 if (myRenderParams.RadianceClampingValue != myRaytraceParameters.RadianceClampingValue
2607 || myRenderParams.UseEnvironmentMapBackground != myRaytraceParameters.UseEnvMapForBackground)
2609 myAccumFrames = 0; // accumulation should be restarted
2611 myRaytraceParameters.RadianceClampingValue = myRenderParams.RadianceClampingValue;
2612 myRaytraceParameters.UseEnvMapForBackground = myRenderParams.UseEnvironmentMapBackground;
2615 else // RT parameters
2617 // Set ambient light source
2618 theProgram->SetUniform (theGlContext,
2619 myUniformLocations[theProgramId][OpenGl_RT_uLightAmbnt], myRaytraceGeometry.Ambient);
2621 // Enable/disable run-time ray-tracing effects
2622 theProgram->SetUniform (theGlContext,
2623 myUniformLocations[theProgramId][OpenGl_RT_uShadowsEnabled], myRenderParams.IsShadowEnabled ? 1 : 0);
2624 theProgram->SetUniform (theGlContext,
2625 myUniformLocations[theProgramId][OpenGl_RT_uReflectEnabled], myRenderParams.IsReflectionEnabled ? 1 : 0);
2628 return Standard_True;
2631 // =======================================================================
2632 // function : bindRaytraceTextures
2633 // purpose : Binds ray-trace textures to corresponding texture units
2634 // =======================================================================
2635 void OpenGl_View::bindRaytraceTextures (const Handle(OpenGl_Context)& theGlContext,
2638 if (myRaytraceParameters.AdaptiveScreenSampling
2639 && myRaytraceParameters.GlobalIllumination)
2641 #if !defined(GL_ES_VERSION_2_0)
2642 theGlContext->core42->glBindImageTexture (OpenGl_RT_OutputImage,
2643 myRaytraceOutputTexture[theStereoView]->TextureId(), 0, GL_TRUE, 0, GL_READ_WRITE, GL_R32F);
2644 theGlContext->core42->glBindImageTexture (OpenGl_RT_VisualErrorImage,
2645 myRaytraceVisualErrorTexture[theStereoView]->TextureId(), 0, GL_TRUE, 0, GL_READ_WRITE, GL_R32I);
2646 if (myRaytraceParameters.AdaptiveScreenSamplingAtomic)
2648 theGlContext->core42->glBindImageTexture (OpenGl_RT_TileOffsetsImage,
2649 myRaytraceTileOffsetsTexture[theStereoView]->TextureId(), 0, GL_TRUE, 0, GL_READ_ONLY, GL_RG32I);
2653 theGlContext->core42->glBindImageTexture (OpenGl_RT_TileSamplesImage,
2654 myRaytraceTileSamplesTexture[theStereoView]->TextureId(), 0, GL_TRUE, 0, GL_READ_WRITE, GL_R32I);
2657 (void )theStereoView;
2661 if (!myTextureEnv.IsNull()
2662 && !myTextureEnv->IsEmpty()
2663 && myTextureEnv->First()->IsValid())
2665 myTextureEnv->First()->Bind (theGlContext, OpenGl_RT_EnvironmentMapTexture);
2668 mySceneMinPointTexture ->BindTexture (theGlContext, OpenGl_RT_SceneMinPointTexture);
2669 mySceneMaxPointTexture ->BindTexture (theGlContext, OpenGl_RT_SceneMaxPointTexture);
2670 mySceneNodeInfoTexture ->BindTexture (theGlContext, OpenGl_RT_SceneNodeInfoTexture);
2671 myGeometryVertexTexture ->BindTexture (theGlContext, OpenGl_RT_GeometryVertexTexture);
2672 myGeometryNormalTexture ->BindTexture (theGlContext, OpenGl_RT_GeometryNormalTexture);
2673 myGeometryTexCrdTexture ->BindTexture (theGlContext, OpenGl_RT_GeometryTexCrdTexture);
2674 myGeometryTriangTexture ->BindTexture (theGlContext, OpenGl_RT_GeometryTriangTexture);
2675 mySceneTransformTexture ->BindTexture (theGlContext, OpenGl_RT_SceneTransformTexture);
2676 myRaytraceMaterialTexture->BindTexture (theGlContext, OpenGl_RT_RaytraceMaterialTexture);
2677 myRaytraceLightSrcTexture->BindTexture (theGlContext, OpenGl_RT_RaytraceLightSrcTexture);
2680 // =======================================================================
2681 // function : unbindRaytraceTextures
2682 // purpose : Unbinds ray-trace textures from corresponding texture units
2683 // =======================================================================
2684 void OpenGl_View::unbindRaytraceTextures (const Handle(OpenGl_Context)& theGlContext)
2686 mySceneMinPointTexture ->UnbindTexture (theGlContext, OpenGl_RT_SceneMinPointTexture);
2687 mySceneMaxPointTexture ->UnbindTexture (theGlContext, OpenGl_RT_SceneMaxPointTexture);
2688 mySceneNodeInfoTexture ->UnbindTexture (theGlContext, OpenGl_RT_SceneNodeInfoTexture);
2689 myGeometryVertexTexture ->UnbindTexture (theGlContext, OpenGl_RT_GeometryVertexTexture);
2690 myGeometryNormalTexture ->UnbindTexture (theGlContext, OpenGl_RT_GeometryNormalTexture);
2691 myGeometryTexCrdTexture ->UnbindTexture (theGlContext, OpenGl_RT_GeometryTexCrdTexture);
2692 myGeometryTriangTexture ->UnbindTexture (theGlContext, OpenGl_RT_GeometryTriangTexture);
2693 mySceneTransformTexture ->UnbindTexture (theGlContext, OpenGl_RT_SceneTransformTexture);
2694 myRaytraceMaterialTexture->UnbindTexture (theGlContext, OpenGl_RT_RaytraceMaterialTexture);
2695 myRaytraceLightSrcTexture->UnbindTexture (theGlContext, OpenGl_RT_RaytraceLightSrcTexture);
2697 theGlContext->core15fwd->glActiveTexture (GL_TEXTURE0);
2700 // =======================================================================
2701 // function : runRaytraceShaders
2702 // purpose : Runs ray-tracing shader programs
2703 // =======================================================================
2704 Standard_Boolean OpenGl_View::runRaytraceShaders (const Standard_Integer theSizeX,
2705 const Standard_Integer theSizeY,
2706 Graphic3d_Camera::Projection theProjection,
2707 OpenGl_FrameBuffer* theReadDrawFbo,
2708 const Handle(OpenGl_Context)& theGlContext)
2710 Standard_Boolean aResult = theGlContext->BindProgram (myRaytraceProgram);
2712 aResult &= setUniformState (0,
2718 if (myRaytraceParameters.GlobalIllumination) // path tracing
2720 aResult &= runPathtrace (theSizeX, theSizeY, theProjection, theGlContext);
2721 aResult &= runPathtraceOut (theProjection, theReadDrawFbo, theGlContext);
2723 else // Whitted-style ray-tracing
2725 aResult &= runRaytrace (theSizeX, theSizeY, theProjection, theReadDrawFbo, theGlContext);
2731 // =======================================================================
2732 // function : runRaytrace
2733 // purpose : Runs Whitted-style ray-tracing
2734 // =======================================================================
2735 Standard_Boolean OpenGl_View::runRaytrace (const Standard_Integer theSizeX,
2736 const Standard_Integer theSizeY,
2737 Graphic3d_Camera::Projection theProjection,
2738 OpenGl_FrameBuffer* theReadDrawFbo,
2739 const Handle(OpenGl_Context)& theGlContext)
2741 Standard_Boolean aResult = Standard_True;
2743 // Choose proper set of frame buffers for stereo rendering
2744 const Standard_Integer aFBOIdx = (theProjection == Graphic3d_Camera::Projection_MonoRightEye) ? 1 : 0;
2745 bindRaytraceTextures (theGlContext, aFBOIdx);
2747 if (myRenderParams.IsAntialiasingEnabled) // if second FSAA pass is used
2749 myRaytraceFBO1[aFBOIdx]->BindBuffer (theGlContext);
2751 glClear (GL_DEPTH_BUFFER_BIT); // render the image with depth
2754 theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
2756 if (myRenderParams.IsAntialiasingEnabled)
2758 glDisable (GL_DEPTH_TEST); // improve jagged edges without depth buffer
2760 // bind ray-tracing output image as input
2761 myRaytraceFBO1[aFBOIdx]->ColorTexture()->Bind (theGlContext, OpenGl_RT_FsaaInputTexture);
2763 aResult &= theGlContext->BindProgram (myPostFSAAProgram);
2765 aResult &= setUniformState (1 /* FSAA ID */,
2771 // Perform multi-pass adaptive FSAA using ping-pong technique.
2772 // We use 'FLIPTRI' sampling pattern changing for every pixel
2773 // (3 additional samples per pixel, the 1st sample is already
2774 // available from initial ray-traced image).
2775 for (Standard_Integer anIt = 1; anIt < 4; ++anIt)
2777 GLfloat aOffsetX = 1.f / theSizeX;
2778 GLfloat aOffsetY = 1.f / theSizeY;
2796 aResult &= myPostFSAAProgram->SetUniform (theGlContext,
2797 myUniformLocations[1][OpenGl_RT_uSamples], anIt + 1);
2798 aResult &= myPostFSAAProgram->SetUniform (theGlContext,
2799 myUniformLocations[1][OpenGl_RT_uOffsetX], aOffsetX);
2800 aResult &= myPostFSAAProgram->SetUniform (theGlContext,
2801 myUniformLocations[1][OpenGl_RT_uOffsetY], aOffsetY);
2803 Handle(OpenGl_FrameBuffer)& aFramebuffer = anIt % 2
2804 ? myRaytraceFBO2[aFBOIdx]
2805 : myRaytraceFBO1[aFBOIdx];
2807 aFramebuffer->BindBuffer (theGlContext);
2809 // perform adaptive FSAA pass
2810 theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
2812 aFramebuffer->ColorTexture()->Bind (theGlContext, OpenGl_RT_FsaaInputTexture);
2815 const Handle(OpenGl_FrameBuffer)& aRenderImageFramebuffer = myRaytraceFBO2[aFBOIdx];
2816 const Handle(OpenGl_FrameBuffer)& aDepthSourceFramebuffer = myRaytraceFBO1[aFBOIdx];
2818 glEnable (GL_DEPTH_TEST);
2820 // Display filtered image
2821 theGlContext->BindProgram (myOutImageProgram);
2823 if (theReadDrawFbo != NULL)
2825 theReadDrawFbo->BindBuffer (theGlContext);
2829 aRenderImageFramebuffer->UnbindBuffer (theGlContext);
2832 aRenderImageFramebuffer->ColorTexture() ->Bind (theGlContext, OpenGl_RT_PrevAccumTexture);
2833 aDepthSourceFramebuffer->DepthStencilTexture()->Bind (theGlContext, OpenGl_RT_RaytraceDepthTexture);
2835 // copy the output image with depth values
2836 theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
2838 aDepthSourceFramebuffer->DepthStencilTexture()->Unbind (theGlContext, OpenGl_RT_RaytraceDepthTexture);
2839 aRenderImageFramebuffer->ColorTexture() ->Unbind (theGlContext, OpenGl_RT_PrevAccumTexture);
2842 unbindRaytraceTextures (theGlContext);
2844 theGlContext->BindProgram (NULL);
2849 // =======================================================================
2850 // function : runPathtrace
2851 // purpose : Runs path tracing shader
2852 // =======================================================================
2853 Standard_Boolean OpenGl_View::runPathtrace (const Standard_Integer theSizeX,
2854 const Standard_Integer theSizeY,
2855 const Graphic3d_Camera::Projection theProjection,
2856 const Handle(OpenGl_Context)& theGlContext)
2858 if (myToUpdateEnvironmentMap) // check whether the map was changed
2860 myAccumFrames = myToUpdateEnvironmentMap = 0;
2863 if (myRenderParams.CameraApertureRadius != myPrevCameraApertureRadius
2864 || myRenderParams.CameraFocalPlaneDist != myPrevCameraFocalPlaneDist)
2866 myPrevCameraApertureRadius = myRenderParams.CameraApertureRadius;
2867 myPrevCameraFocalPlaneDist = myRenderParams.CameraFocalPlaneDist;
2871 // Choose proper set of frame buffers for stereo rendering
2872 const Standard_Integer aFBOIdx = (theProjection == Graphic3d_Camera::Projection_MonoRightEye) ? 1 : 0;
2874 if (myRaytraceParameters.AdaptiveScreenSampling)
2876 if (myAccumFrames == 0)
2878 myTileSampler.Reset(); // reset tile sampler to its initial state
2880 // Adaptive sampling is starting at the second frame
2881 if (myRaytraceParameters.AdaptiveScreenSamplingAtomic)
2883 myTileSampler.UploadOffsets (theGlContext, myRaytraceTileOffsetsTexture[aFBOIdx], false);
2887 myTileSampler.UploadSamples (theGlContext, myRaytraceTileSamplesTexture[aFBOIdx], false);
2890 #if !defined(GL_ES_VERSION_2_0)
2891 theGlContext->core44->glClearTexImage (myRaytraceOutputTexture[aFBOIdx]->TextureId(), 0, GL_RED, GL_FLOAT, NULL);
2895 // Clear adaptive screen sampling images
2896 #if !defined(GL_ES_VERSION_2_0)
2897 theGlContext->core44->glClearTexImage (myRaytraceVisualErrorTexture[aFBOIdx]->TextureId(), 0, GL_RED_INTEGER, GL_INT, NULL);
2901 bindRaytraceTextures (theGlContext, aFBOIdx);
2903 const Handle(OpenGl_FrameBuffer)& anAccumImageFramebuffer = myAccumFrames % 2 ? myRaytraceFBO2[aFBOIdx] : myRaytraceFBO1[aFBOIdx];
2904 anAccumImageFramebuffer->ColorTexture()->Bind (theGlContext, OpenGl_RT_PrevAccumTexture);
2906 // Set frame accumulation weight
2907 myRaytraceProgram->SetUniform (theGlContext, myUniformLocations[0][OpenGl_RT_uAccumSamples], myAccumFrames);
2909 // Set image uniforms for render program
2910 if (myRaytraceParameters.AdaptiveScreenSampling)
2912 myRaytraceProgram->SetUniform (theGlContext, myUniformLocations[0][OpenGl_RT_uRenderImage], OpenGl_RT_OutputImage);
2913 myRaytraceProgram->SetUniform (theGlContext, myUniformLocations[0][OpenGl_RT_uTilesImage], OpenGl_RT_TileSamplesImage);
2914 myRaytraceProgram->SetUniform (theGlContext, myUniformLocations[0][OpenGl_RT_uOffsetImage], OpenGl_RT_TileOffsetsImage);
2915 myRaytraceProgram->SetUniform (theGlContext, myUniformLocations[0][OpenGl_RT_uTileSize], myTileSampler.TileSize());
2918 const Handle(OpenGl_FrameBuffer)& aRenderImageFramebuffer = myAccumFrames % 2 ? myRaytraceFBO1[aFBOIdx] : myRaytraceFBO2[aFBOIdx];
2919 aRenderImageFramebuffer->BindBuffer (theGlContext);
2920 if (myRaytraceParameters.AdaptiveScreenSampling
2921 && myRaytraceParameters.AdaptiveScreenSamplingAtomic)
2923 // extend viewport here, so that tiles at boundaries (cut tile size by target rendering viewport)
2924 // redirected to inner tiles (full tile size) are drawn entirely
2925 const Graphic3d_Vec2i anOffsetViewport = myTileSampler.OffsetTilesViewport (myAccumFrames > 1); // shrunk offsets texture will be uploaded since 3rd frame
2926 glViewport (0, 0, anOffsetViewport.x(), anOffsetViewport.y());
2929 // Generate for the given RNG seed
2930 glDisable (GL_DEPTH_TEST);
2932 // Adaptive Screen Sampling computes the same overall amount of samples per frame redraw as normal Path Tracing,
2933 // but distributes them unequally across pixels (grouped in tiles), so that some pixels do not receive new samples at all.
2935 // Offsets map (redirecting currently rendered tile to another tile) allows performing Adaptive Screen Sampling in single pass,
2936 // but current implementation relies on atomic float operations (AdaptiveScreenSamplingAtomic) for this.
2937 // So that when atomic floats are not supported by GPU, multi-pass rendering is used instead.
2939 // Single-pass rendering is more optimal due to smaller amount of draw calls,
2940 // memory synchronization barriers, discarding most of the fragments and bad parallelization in case of very small amount of tiles requiring more samples.
2941 // However, atomic operations on float values still produces different result (close, but not bit exact) making non-regression testing not robust.
2942 // It should be possible following single-pass rendering approach but using extra accumulation buffer and resolving pass as possible improvement.
2943 const int aNbPasses = myRaytraceParameters.AdaptiveScreenSampling
2944 && !myRaytraceParameters.AdaptiveScreenSamplingAtomic
2945 ? myTileSampler.MaxTileSamples()
2947 if (myAccumFrames == 0)
2949 myRNG.SetSeed(); // start RNG from beginning
2951 for (int aPassIter = 0; aPassIter < aNbPasses; ++aPassIter)
2953 myRaytraceProgram->SetUniform (theGlContext, myUniformLocations[0][OpenGl_RT_uFrameRndSeed], static_cast<Standard_Integer> (myRNG.NextInt() >> 2));
2954 theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
2955 if (myRaytraceParameters.AdaptiveScreenSampling)
2957 #if !defined(GL_ES_VERSION_2_0)
2958 theGlContext->core44->glMemoryBarrier (GL_SHADER_IMAGE_ACCESS_BARRIER_BIT);
2962 aRenderImageFramebuffer->UnbindBuffer (theGlContext);
2964 if (myRaytraceParameters.AdaptiveScreenSampling
2965 && myRaytraceParameters.AdaptiveScreenSamplingAtomic)
2967 glViewport (0, 0, theSizeX, theSizeY);
2972 // =======================================================================
2973 // function : runPathtraceOut
2975 // =======================================================================
2976 Standard_Boolean OpenGl_View::runPathtraceOut (const Graphic3d_Camera::Projection theProjection,
2977 OpenGl_FrameBuffer* theReadDrawFbo,
2978 const Handle(OpenGl_Context)& theGlContext)
2980 // Output accumulated path traced image
2981 theGlContext->BindProgram (myOutImageProgram);
2983 // Choose proper set of frame buffers for stereo rendering
2984 const Standard_Integer aFBOIdx = (theProjection == Graphic3d_Camera::Projection_MonoRightEye) ? 1 : 0;
2986 if (myRaytraceParameters.AdaptiveScreenSampling)
2988 // Set uniforms for display program
2989 myOutImageProgram->SetUniform (theGlContext, "uRenderImage", OpenGl_RT_OutputImage);
2990 myOutImageProgram->SetUniform (theGlContext, "uAccumFrames", myAccumFrames);
2991 myOutImageProgram->SetUniform (theGlContext, "uVarianceImage", OpenGl_RT_VisualErrorImage);
2992 myOutImageProgram->SetUniform (theGlContext, "uDebugAdaptive", myRenderParams.ShowSamplingTiles ? 1 : 0);
2993 myOutImageProgram->SetUniform (theGlContext, "uTileSize", myTileSampler.TileSize());
2994 myOutImageProgram->SetUniform (theGlContext, "uVarianceScaleFactor", myTileSampler.VarianceScaleFactor());
2997 if (myRaytraceParameters.GlobalIllumination)
2999 myOutImageProgram->SetUniform(theGlContext, "uExposure", myRenderParams.Exposure);
3000 switch (myRaytraceParameters.ToneMappingMethod)
3002 case Graphic3d_ToneMappingMethod_Disabled:
3004 case Graphic3d_ToneMappingMethod_Filmic:
3005 myOutImageProgram->SetUniform (theGlContext, "uWhitePoint", myRenderParams.WhitePoint);
3010 if (theReadDrawFbo != NULL)
3012 theReadDrawFbo->BindBuffer (theGlContext);
3015 const Handle(OpenGl_FrameBuffer)& aRenderImageFramebuffer = myAccumFrames % 2 ? myRaytraceFBO1[aFBOIdx] : myRaytraceFBO2[aFBOIdx];
3016 aRenderImageFramebuffer->ColorTexture()->Bind (theGlContext, OpenGl_RT_PrevAccumTexture);
3018 // Copy accumulated image with correct depth values
3019 glEnable (GL_DEPTH_TEST);
3020 theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
3022 aRenderImageFramebuffer->ColorTexture()->Unbind (theGlContext, OpenGl_RT_PrevAccumTexture);
3024 if (myRaytraceParameters.AdaptiveScreenSampling)
3026 // Download visual error map from the GPU and build adjusted tile offsets for optimal image sampling
3027 myTileSampler.GrabVarianceMap (theGlContext, myRaytraceVisualErrorTexture[aFBOIdx]);
3028 if (myRaytraceParameters.AdaptiveScreenSamplingAtomic)
3030 myTileSampler.UploadOffsets (theGlContext, myRaytraceTileOffsetsTexture[aFBOIdx], myAccumFrames != 0);
3034 myTileSampler.UploadSamples (theGlContext, myRaytraceTileSamplesTexture[aFBOIdx], myAccumFrames != 0);
3038 unbindRaytraceTextures (theGlContext);
3039 theGlContext->BindProgram (NULL);
3043 // =======================================================================
3044 // function : raytrace
3045 // purpose : Redraws the window using OpenGL/GLSL ray-tracing
3046 // =======================================================================
3047 Standard_Boolean OpenGl_View::raytrace (const Standard_Integer theSizeX,
3048 const Standard_Integer theSizeY,
3049 Graphic3d_Camera::Projection theProjection,
3050 OpenGl_FrameBuffer* theReadDrawFbo,
3051 const Handle(OpenGl_Context)& theGlContext)
3053 if (!initRaytraceResources (theSizeX, theSizeY, theGlContext))
3055 return Standard_False;
3058 if (!updateRaytraceBuffers (theSizeX, theSizeY, theGlContext))
3060 return Standard_False;
3063 OpenGl_Mat4 aLightSourceMatrix;
3065 // Get inversed model-view matrix for transforming lights
3066 myCamera->OrientationMatrixF().Inverted (aLightSourceMatrix);
3068 if (!updateRaytraceLightSources (aLightSourceMatrix, theGlContext))
3070 return Standard_False;
3073 // Generate image using Whitted-style ray-tracing or path tracing
3074 if (myIsRaytraceDataValid)
3076 myRaytraceScreenQuad.BindVertexAttrib (theGlContext, Graphic3d_TOA_POS);
3078 if (!myRaytraceGeometry.AcquireTextures (theGlContext))
3080 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR,
3081 0, GL_DEBUG_SEVERITY_MEDIUM, "Error: Failed to acquire OpenGL image textures");
3084 glDisable (GL_BLEND);
3086 const Standard_Boolean aResult = runRaytraceShaders (theSizeX,
3094 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR,
3095 0, GL_DEBUG_SEVERITY_MEDIUM, "Error: Failed to execute ray-tracing shaders");
3098 if (!myRaytraceGeometry.ReleaseTextures (theGlContext))
3100 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR,
3101 0, GL_DEBUG_SEVERITY_MEDIUM, "Error: Failed to release OpenGL image textures");
3104 myRaytraceScreenQuad.UnbindVertexAttrib (theGlContext, Graphic3d_TOA_POS);
3107 return Standard_True;