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 aResMat.Ambient = theGlContext->Vec4FromQuantityColor (aResMat.Ambient);
397 aResMat.Diffuse = theGlContext->Vec4FromQuantityColor (aResMat.Diffuse);
398 aResMat.Specular = theGlContext->Vec4FromQuantityColor (aResMat.Specular);
399 aResMat.Emission = theGlContext->Vec4FromQuantityColor (aResMat.Emission);
401 // Serialize physically-based material properties
402 const Graphic3d_BSDF& aBSDF = aSrcMat.BSDF();
404 aResMat.BSDF.Kc = aBSDF.Kc;
405 aResMat.BSDF.Ks = aBSDF.Ks;
406 aResMat.BSDF.Kd = BVH_Vec4f (aBSDF.Kd, -1.f); // no texture
407 aResMat.BSDF.Kt = BVH_Vec4f (aBSDF.Kt, 0.f);
408 aResMat.BSDF.Le = BVH_Vec4f (aBSDF.Le, 0.f);
410 aResMat.BSDF.Absorption = aBSDF.Absorption;
412 aResMat.BSDF.FresnelCoat = aBSDF.FresnelCoat.Serialize ();
413 aResMat.BSDF.FresnelBase = aBSDF.FresnelBase.Serialize ();
415 // Handle material textures
416 if (!theAspect->Aspect()->ToMapTexture())
421 const Handle(OpenGl_TextureSet)& aTextureSet = theAspect->TextureSet (theGlContext);
422 if (aTextureSet.IsNull()
423 || aTextureSet->IsEmpty()
424 || aTextureSet->First().IsNull())
429 if (theGlContext->HasRayTracingTextures())
431 const Handle(OpenGl_Texture)& aTexture = aTextureSet->First();
432 buildTextureTransform (aTexture->Sampler()->Parameters(), aResMat.TextureTransform);
434 // write texture ID to diffuse w-component
435 aResMat.Diffuse.w() = aResMat.BSDF.Kd.w() = static_cast<Standard_ShortReal> (myRaytraceGeometry.AddTexture (aTexture));
437 else if (!myIsRaytraceWarnTextures)
439 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_PORTABILITY, 0, GL_DEBUG_SEVERITY_HIGH,
440 "Warning: texturing in Ray-Trace requires GL_ARB_bindless_texture extension which is missing. "
441 "Please try to update graphics card driver. At the moment textures will be ignored.");
442 myIsRaytraceWarnTextures = Standard_True;
448 // =======================================================================
449 // function : addRaytraceStructure
450 // purpose : Adds OpenGL structure to ray-traced scene geometry
451 // =======================================================================
452 Standard_Boolean OpenGl_View::addRaytraceStructure (const OpenGl_Structure* theStructure,
453 const Handle(OpenGl_Context)& theGlContext)
455 if (!theStructure->IsVisible())
457 myStructureStates[theStructure] = StructState (theStructure);
459 return Standard_True;
462 // Get structure material
463 OpenGl_RaytraceMaterial aDefaultMaterial;
464 Standard_Boolean aResult = addRaytraceGroups (theStructure, aDefaultMaterial, theStructure->Transformation(), theGlContext);
466 // Process all connected OpenGL structures
467 const OpenGl_Structure* anInstanced = theStructure->InstancedStructure();
469 if (anInstanced != NULL && anInstanced->IsRaytracable())
471 aResult &= addRaytraceGroups (anInstanced, aDefaultMaterial, theStructure->Transformation(), theGlContext);
474 myStructureStates[theStructure] = StructState (theStructure);
479 // =======================================================================
480 // function : addRaytraceGroups
481 // purpose : Adds OpenGL groups to ray-traced scene geometry
482 // =======================================================================
483 Standard_Boolean OpenGl_View::addRaytraceGroups (const OpenGl_Structure* theStructure,
484 const OpenGl_RaytraceMaterial& theStructMat,
485 const Handle(Geom_Transformation)& theTrsf,
486 const Handle(OpenGl_Context)& theGlContext)
489 for (OpenGl_Structure::GroupIterator aGroupIter (theStructure->Groups()); aGroupIter.More(); aGroupIter.Next())
491 // Get group material
492 OpenGl_RaytraceMaterial aGroupMaterial;
493 if (aGroupIter.Value()->GlAspects() != NULL)
495 aGroupMaterial = convertMaterial (aGroupIter.Value()->GlAspects(), theGlContext);
498 Standard_Integer aMatID = static_cast<Standard_Integer> (myRaytraceGeometry.Materials.size());
500 // Use group material if available, otherwise use structure material
501 myRaytraceGeometry.Materials.push_back (aGroupIter.Value()->GlAspects() != NULL ? aGroupMaterial : theStructMat);
503 // Add OpenGL elements from group (extract primitives arrays and aspects)
504 for (const OpenGl_ElementNode* aNode = aGroupIter.Value()->FirstNode(); aNode != NULL; aNode = aNode->next)
506 OpenGl_Aspects* anAspect = dynamic_cast<OpenGl_Aspects*> (aNode->elem);
508 if (anAspect != NULL)
510 aMatID = static_cast<Standard_Integer> (myRaytraceGeometry.Materials.size());
512 OpenGl_RaytraceMaterial aMaterial = convertMaterial (anAspect, theGlContext);
514 myRaytraceGeometry.Materials.push_back (aMaterial);
518 OpenGl_PrimitiveArray* aPrimArray = dynamic_cast<OpenGl_PrimitiveArray*> (aNode->elem);
520 if (aPrimArray != NULL)
522 std::map<Standard_Size, OpenGl_TriangleSet*>::iterator aSetIter = myArrayToTrianglesMap.find (aPrimArray->GetUID());
524 if (aSetIter != myArrayToTrianglesMap.end())
526 OpenGl_TriangleSet* aSet = aSetIter->second;
527 opencascade::handle<BVH_Transform<Standard_ShortReal, 4> > aTransform = new BVH_Transform<Standard_ShortReal, 4>();
528 if (!theTrsf.IsNull())
530 theTrsf->Trsf().GetMat4 (aMat4);
531 aTransform->SetTransform (aMat4);
534 aSet->SetProperties (aTransform);
535 if (aSet->MaterialIndex() != OpenGl_TriangleSet::INVALID_MATERIAL && aSet->MaterialIndex() != aMatID)
537 aSet->SetMaterialIndex (aMatID);
542 if (Handle(OpenGl_TriangleSet) aSet = addRaytracePrimitiveArray (aPrimArray, aMatID, 0))
544 opencascade::handle<BVH_Transform<Standard_ShortReal, 4> > aTransform = new BVH_Transform<Standard_ShortReal, 4>();
545 if (!theTrsf.IsNull())
547 theTrsf->Trsf().GetMat4 (aMat4);
548 aTransform->SetTransform (aMat4);
551 aSet->SetProperties (aTransform);
552 myRaytraceGeometry.Objects().Append (aSet);
560 return Standard_True;
563 // =======================================================================
564 // function : addRaytracePrimitiveArray
565 // purpose : Adds OpenGL primitive array to ray-traced scene geometry
566 // =======================================================================
567 Handle(OpenGl_TriangleSet) OpenGl_View::addRaytracePrimitiveArray (const OpenGl_PrimitiveArray* theArray,
568 const Standard_Integer theMaterial,
569 const OpenGl_Mat4* theTransform)
571 const Handle(Graphic3d_BoundBuffer)& aBounds = theArray->Bounds();
572 const Handle(Graphic3d_IndexBuffer)& anIndices = theArray->Indices();
573 const Handle(Graphic3d_Buffer)& anAttribs = theArray->Attributes();
575 if (theArray->DrawMode() < GL_TRIANGLES
576 #ifndef GL_ES_VERSION_2_0
577 || theArray->DrawMode() > GL_POLYGON
579 || theArray->DrawMode() > GL_TRIANGLE_FAN
581 || anAttribs.IsNull())
583 return Handle(OpenGl_TriangleSet)();
586 OpenGl_Mat4 aNormalMatrix;
587 if (theTransform != NULL)
589 Standard_ASSERT_RETURN (theTransform->Inverted (aNormalMatrix),
590 "Error: Failed to compute normal transformation matrix", NULL);
592 aNormalMatrix.Transpose();
595 Handle(OpenGl_TriangleSet) aSet = new OpenGl_TriangleSet (theArray->GetUID(), myRaytraceBVHBuilder);
597 aSet->Vertices.reserve (anAttribs->NbElements);
598 aSet->Normals.reserve (anAttribs->NbElements);
599 aSet->TexCrds.reserve (anAttribs->NbElements);
601 const size_t aVertFrom = aSet->Vertices.size();
603 Standard_Integer anAttribIndex = 0;
604 Standard_Size anAttribStride = 0;
605 if (const Standard_Byte* aPosData = anAttribs->AttributeData (Graphic3d_TOA_POS, anAttribIndex, anAttribStride))
607 const Graphic3d_Attribute& anAttrib = anAttribs->Attribute (anAttribIndex);
608 if (anAttrib.DataType == Graphic3d_TOD_VEC2
609 || anAttrib.DataType == Graphic3d_TOD_VEC3
610 || anAttrib.DataType == Graphic3d_TOD_VEC4)
612 for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
614 const float* aCoords = reinterpret_cast<const float*> (aPosData + anAttribStride * aVertIter);
615 aSet->Vertices.push_back (BVH_Vec3f (aCoords[0], aCoords[1], anAttrib.DataType != Graphic3d_TOD_VEC2 ? aCoords[2] : 0.0f));
619 if (const Standard_Byte* aNormData = anAttribs->AttributeData (Graphic3d_TOA_NORM, anAttribIndex, anAttribStride))
621 const Graphic3d_Attribute& anAttrib = anAttribs->Attribute (anAttribIndex);
622 if (anAttrib.DataType == Graphic3d_TOD_VEC3
623 || anAttrib.DataType == Graphic3d_TOD_VEC4)
625 for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
627 aSet->Normals.push_back (*reinterpret_cast<const Graphic3d_Vec3*> (aNormData + anAttribStride * aVertIter));
631 if (const Standard_Byte* aTexData = anAttribs->AttributeData (Graphic3d_TOA_UV, anAttribIndex, anAttribStride))
633 const Graphic3d_Attribute& anAttrib = anAttribs->Attribute (anAttribIndex);
634 if (anAttrib.DataType == Graphic3d_TOD_VEC2)
636 for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
638 aSet->TexCrds.push_back (*reinterpret_cast<const Graphic3d_Vec2*> (aTexData + anAttribStride * aVertIter));
643 if (aSet->Normals.size() != aSet->Vertices.size())
645 for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
647 aSet->Normals.push_back (BVH_Vec3f());
651 if (aSet->TexCrds.size() != aSet->Vertices.size())
653 for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
655 aSet->TexCrds.push_back (BVH_Vec2f());
659 if (theTransform != NULL)
661 for (size_t aVertIter = aVertFrom; aVertIter < aSet->Vertices.size(); ++aVertIter)
663 BVH_Vec3f& aVertex = aSet->Vertices[aVertIter];
665 BVH_Vec4f aTransVertex = *theTransform *
666 BVH_Vec4f (aVertex.x(), aVertex.y(), aVertex.z(), 1.f);
668 aVertex = BVH_Vec3f (aTransVertex.x(), aTransVertex.y(), aTransVertex.z());
670 for (size_t aVertIter = aVertFrom; aVertIter < aSet->Normals.size(); ++aVertIter)
672 BVH_Vec3f& aNormal = aSet->Normals[aVertIter];
674 BVH_Vec4f aTransNormal = aNormalMatrix *
675 BVH_Vec4f (aNormal.x(), aNormal.y(), aNormal.z(), 0.f);
677 aNormal = BVH_Vec3f (aTransNormal.x(), aTransNormal.y(), aTransNormal.z());
681 if (!aBounds.IsNull())
683 for (Standard_Integer aBound = 0, aBoundStart = 0; aBound < aBounds->NbBounds; ++aBound)
685 const Standard_Integer aVertNum = aBounds->Bounds[aBound];
687 if (!addRaytraceVertexIndices (*aSet, theMaterial, aVertNum, aBoundStart, *theArray))
690 return Handle(OpenGl_TriangleSet)();
693 aBoundStart += aVertNum;
698 const Standard_Integer aVertNum = !anIndices.IsNull() ? anIndices->NbElements : anAttribs->NbElements;
700 if (!addRaytraceVertexIndices (*aSet, theMaterial, aVertNum, 0, *theArray))
703 return Handle(OpenGl_TriangleSet)();
708 if (aSet->Size() != 0)
716 // =======================================================================
717 // function : addRaytraceVertexIndices
718 // purpose : Adds vertex indices to ray-traced scene geometry
719 // =======================================================================
720 Standard_Boolean OpenGl_View::addRaytraceVertexIndices (OpenGl_TriangleSet& theSet,
721 const Standard_Integer theMatID,
722 const Standard_Integer theCount,
723 const Standard_Integer theOffset,
724 const OpenGl_PrimitiveArray& theArray)
726 switch (theArray.DrawMode())
728 case GL_TRIANGLES: return addRaytraceTriangleArray (theSet, theMatID, theCount, theOffset, theArray.Indices());
729 case GL_TRIANGLE_FAN: return addRaytraceTriangleFanArray (theSet, theMatID, theCount, theOffset, theArray.Indices());
730 case GL_TRIANGLE_STRIP: return addRaytraceTriangleStripArray (theSet, theMatID, theCount, theOffset, theArray.Indices());
731 #if !defined(GL_ES_VERSION_2_0)
732 case GL_QUAD_STRIP: return addRaytraceQuadrangleStripArray (theSet, theMatID, theCount, theOffset, theArray.Indices());
733 case GL_QUADS: return addRaytraceQuadrangleArray (theSet, theMatID, theCount, theOffset, theArray.Indices());
734 case GL_POLYGON: return addRaytracePolygonArray (theSet, theMatID, theCount, theOffset, theArray.Indices());
738 return Standard_False;
741 // =======================================================================
742 // function : addRaytraceTriangleArray
743 // purpose : Adds OpenGL triangle array to ray-traced scene geometry
744 // =======================================================================
745 Standard_Boolean OpenGl_View::addRaytraceTriangleArray (OpenGl_TriangleSet& theSet,
746 const Standard_Integer theMatID,
747 const Standard_Integer theCount,
748 const Standard_Integer theOffset,
749 const Handle(Graphic3d_IndexBuffer)& theIndices)
753 return Standard_True;
756 theSet.Elements.reserve (theSet.Elements.size() + theCount / 3);
758 if (!theIndices.IsNull())
760 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; aVert += 3)
762 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0),
763 theIndices->Index (aVert + 1),
764 theIndices->Index (aVert + 2),
770 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; aVert += 3)
772 theSet.Elements.push_back (BVH_Vec4i (aVert + 0, aVert + 1, aVert + 2, theMatID));
776 return Standard_True;
779 // =======================================================================
780 // function : addRaytraceTriangleFanArray
781 // purpose : Adds OpenGL triangle fan array to ray-traced scene geometry
782 // =======================================================================
783 Standard_Boolean OpenGl_View::addRaytraceTriangleFanArray (OpenGl_TriangleSet& theSet,
784 const Standard_Integer theMatID,
785 const Standard_Integer theCount,
786 const Standard_Integer theOffset,
787 const Handle(Graphic3d_IndexBuffer)& theIndices)
791 return Standard_True;
794 theSet.Elements.reserve (theSet.Elements.size() + theCount - 2);
796 if (!theIndices.IsNull())
798 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
800 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (theOffset),
801 theIndices->Index (aVert + 1),
802 theIndices->Index (aVert + 2),
808 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
810 theSet.Elements.push_back (BVH_Vec4i (theOffset,
817 return Standard_True;
820 // =======================================================================
821 // function : addRaytraceTriangleStripArray
822 // purpose : Adds OpenGL triangle strip array to ray-traced scene geometry
823 // =======================================================================
824 Standard_Boolean OpenGl_View::addRaytraceTriangleStripArray (OpenGl_TriangleSet& theSet,
825 const Standard_Integer theMatID,
826 const Standard_Integer theCount,
827 const Standard_Integer theOffset,
828 const Handle(Graphic3d_IndexBuffer)& theIndices)
832 return Standard_True;
835 theSet.Elements.reserve (theSet.Elements.size() + theCount - 2);
837 if (!theIndices.IsNull())
839 for (Standard_Integer aVert = theOffset, aCW = 0; aVert < theOffset + theCount - 2; ++aVert, aCW = (aCW + 1) % 2)
841 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + (aCW ? 1 : 0)),
842 theIndices->Index (aVert + (aCW ? 0 : 1)),
843 theIndices->Index (aVert + 2),
849 for (Standard_Integer aVert = theOffset, aCW = 0; aVert < theOffset + theCount - 2; ++aVert, aCW = (aCW + 1) % 2)
851 theSet.Elements.push_back (BVH_Vec4i (aVert + (aCW ? 1 : 0),
852 aVert + (aCW ? 0 : 1),
858 return Standard_True;
861 // =======================================================================
862 // function : addRaytraceQuadrangleArray
863 // purpose : Adds OpenGL quad array to ray-traced scene geometry
864 // =======================================================================
865 Standard_Boolean OpenGl_View::addRaytraceQuadrangleArray (OpenGl_TriangleSet& theSet,
866 const Standard_Integer theMatID,
867 const Standard_Integer theCount,
868 const Standard_Integer theOffset,
869 const Handle(Graphic3d_IndexBuffer)& theIndices)
873 return Standard_True;
876 theSet.Elements.reserve (theSet.Elements.size() + theCount / 2);
878 if (!theIndices.IsNull())
880 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 4)
882 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0),
883 theIndices->Index (aVert + 1),
884 theIndices->Index (aVert + 2),
886 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0),
887 theIndices->Index (aVert + 2),
888 theIndices->Index (aVert + 3),
894 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 4)
896 theSet.Elements.push_back (BVH_Vec4i (aVert + 0, aVert + 1, aVert + 2,
898 theSet.Elements.push_back (BVH_Vec4i (aVert + 0, aVert + 2, aVert + 3,
903 return Standard_True;
906 // =======================================================================
907 // function : addRaytraceQuadrangleStripArray
908 // purpose : Adds OpenGL quad strip array to ray-traced scene geometry
909 // =======================================================================
910 Standard_Boolean OpenGl_View::addRaytraceQuadrangleStripArray (OpenGl_TriangleSet& theSet,
911 const Standard_Integer theMatID,
912 const Standard_Integer theCount,
913 const Standard_Integer theOffset,
914 const Handle(Graphic3d_IndexBuffer)& theIndices)
918 return Standard_True;
921 theSet.Elements.reserve (theSet.Elements.size() + 2 * theCount - 6);
923 if (!theIndices.IsNull())
925 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 2)
927 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0),
928 theIndices->Index (aVert + 1),
929 theIndices->Index (aVert + 2),
932 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 1),
933 theIndices->Index (aVert + 3),
934 theIndices->Index (aVert + 2),
940 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 2)
942 theSet.Elements.push_back (BVH_Vec4i (aVert + 0,
947 theSet.Elements.push_back (BVH_Vec4i (aVert + 1,
954 return Standard_True;
957 // =======================================================================
958 // function : addRaytracePolygonArray
959 // purpose : Adds OpenGL polygon array to ray-traced scene geometry
960 // =======================================================================
961 Standard_Boolean OpenGl_View::addRaytracePolygonArray (OpenGl_TriangleSet& theSet,
962 const Standard_Integer theMatID,
963 const Standard_Integer theCount,
964 const Standard_Integer theOffset,
965 const Handle(Graphic3d_IndexBuffer)& theIndices)
969 return Standard_True;
972 theSet.Elements.reserve (theSet.Elements.size() + theCount - 2);
974 if (!theIndices.IsNull())
976 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
978 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (theOffset),
979 theIndices->Index (aVert + 1),
980 theIndices->Index (aVert + 2),
986 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
988 theSet.Elements.push_back (BVH_Vec4i (theOffset,
995 return Standard_True;
998 const TCollection_AsciiString OpenGl_View::ShaderSource::EMPTY_PREFIX;
1000 // =======================================================================
1001 // function : Source
1002 // purpose : Returns shader source combined with prefix
1003 // =======================================================================
1004 TCollection_AsciiString OpenGl_View::ShaderSource::Source() const
1006 const TCollection_AsciiString aVersion = "#version 140";
1008 if (myPrefix.IsEmpty())
1010 return aVersion + "\n" + mySource;
1013 return aVersion + "\n" + myPrefix + "\n" + mySource;
1016 // =======================================================================
1017 // function : LoadFromFiles
1018 // purpose : Loads shader source from specified files
1019 // =======================================================================
1020 Standard_Boolean OpenGl_View::ShaderSource::LoadFromFiles (const TCollection_AsciiString* theFileNames,
1021 const TCollection_AsciiString& thePrefix)
1025 myPrefix = thePrefix;
1027 TCollection_AsciiString aMissingFiles;
1028 for (Standard_Integer anIndex = 0; !theFileNames[anIndex].IsEmpty(); ++anIndex)
1030 OSD_File aFile (theFileNames[anIndex]);
1033 aFile.Open (OSD_ReadOnly, OSD_Protection());
1035 if (!aFile.IsOpen())
1037 if (!aMissingFiles.IsEmpty())
1039 aMissingFiles += ", ";
1041 aMissingFiles += TCollection_AsciiString("'") + theFileNames[anIndex] + "'";
1044 else if (!aMissingFiles.IsEmpty())
1050 TCollection_AsciiString aSource;
1051 aFile.Read (aSource, (Standard_Integer) aFile.Size());
1052 if (!aSource.IsEmpty())
1054 mySource += TCollection_AsciiString ("\n") + aSource;
1059 if (!aMissingFiles.IsEmpty())
1061 myError = TCollection_AsciiString("Shader files ") + aMissingFiles + " are missing or inaccessible";
1062 return Standard_False;
1064 return Standard_True;
1067 // =======================================================================
1068 // function : LoadFromStrings
1070 // =======================================================================
1071 Standard_Boolean OpenGl_View::ShaderSource::LoadFromStrings (const TCollection_AsciiString* theStrings,
1072 const TCollection_AsciiString& thePrefix)
1076 myPrefix = thePrefix;
1078 for (Standard_Integer anIndex = 0; !theStrings[anIndex].IsEmpty(); ++anIndex)
1080 TCollection_AsciiString aSource = theStrings[anIndex];
1081 if (!aSource.IsEmpty())
1083 mySource += TCollection_AsciiString ("\n") + aSource;
1086 return Standard_True;
1089 // =======================================================================
1090 // function : generateShaderPrefix
1091 // purpose : Generates shader prefix based on current ray-tracing options
1092 // =======================================================================
1093 TCollection_AsciiString OpenGl_View::generateShaderPrefix (const Handle(OpenGl_Context)& theGlContext) const
1095 TCollection_AsciiString aPrefixString =
1096 TCollection_AsciiString ("#define STACK_SIZE ") + TCollection_AsciiString (myRaytraceParameters.StackSize) + "\n" +
1097 TCollection_AsciiString ("#define NB_BOUNCES ") + TCollection_AsciiString (myRaytraceParameters.NbBounces);
1099 if (myRaytraceParameters.TransparentShadows)
1101 aPrefixString += TCollection_AsciiString ("\n#define TRANSPARENT_SHADOWS");
1103 if (!theGlContext->ToRenderSRGB())
1105 aPrefixString += TCollection_AsciiString ("\n#define THE_SHIFT_sRGB");
1108 // If OpenGL driver supports bindless textures and texturing
1109 // is actually used, activate texturing in ray-tracing mode
1110 if (myRaytraceParameters.UseBindlessTextures && theGlContext->arbTexBindless != NULL)
1112 aPrefixString += TCollection_AsciiString ("\n#define USE_TEXTURES") +
1113 TCollection_AsciiString ("\n#define MAX_TEX_NUMBER ") + TCollection_AsciiString (OpenGl_RaytraceGeometry::MAX_TEX_NUMBER);
1116 if (myRaytraceParameters.GlobalIllumination) // path tracing activated
1118 aPrefixString += TCollection_AsciiString ("\n#define PATH_TRACING");
1120 if (myRaytraceParameters.AdaptiveScreenSampling) // adaptive screen sampling requested
1122 if (theGlContext->IsGlGreaterEqual (4, 4))
1124 aPrefixString += TCollection_AsciiString ("\n#define ADAPTIVE_SAMPLING");
1125 if (myRaytraceParameters.AdaptiveScreenSamplingAtomic
1126 && theGlContext->CheckExtension ("GL_NV_shader_atomic_float"))
1128 aPrefixString += TCollection_AsciiString ("\n#define ADAPTIVE_SAMPLING_ATOMIC");
1133 if (myRaytraceParameters.TwoSidedBsdfModels) // two-sided BSDFs requested
1135 aPrefixString += TCollection_AsciiString ("\n#define TWO_SIDED_BXDF");
1138 switch (myRaytraceParameters.ToneMappingMethod)
1140 case Graphic3d_ToneMappingMethod_Disabled:
1142 case Graphic3d_ToneMappingMethod_Filmic:
1143 aPrefixString += TCollection_AsciiString ("\n#define TONE_MAPPING_FILMIC");
1148 if (myRaytraceParameters.DepthOfField)
1150 aPrefixString += TCollection_AsciiString("\n#define DEPTH_OF_FIELD");
1153 return aPrefixString;
1156 // =======================================================================
1157 // function : safeFailBack
1158 // purpose : Performs safe exit when shaders initialization fails
1159 // =======================================================================
1160 Standard_Boolean OpenGl_View::safeFailBack (const TCollection_ExtendedString& theMessage,
1161 const Handle(OpenGl_Context)& theGlContext)
1163 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1164 GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, theMessage);
1166 myRaytraceInitStatus = OpenGl_RT_FAIL;
1168 releaseRaytraceResources (theGlContext);
1170 return Standard_False;
1173 // =======================================================================
1174 // function : initShader
1175 // purpose : Creates new shader object with specified source
1176 // =======================================================================
1177 Handle(OpenGl_ShaderObject) OpenGl_View::initShader (const GLenum theType,
1178 const ShaderSource& theSource,
1179 const Handle(OpenGl_Context)& theGlContext)
1181 Handle(OpenGl_ShaderObject) aShader = new OpenGl_ShaderObject (theType);
1182 if (!aShader->Create (theGlContext))
1184 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH,
1185 TCollection_ExtendedString ("Error: Failed to create ") +
1186 (theType == GL_VERTEX_SHADER ? "vertex" : "fragment") + " shader object");
1187 aShader->Release (theGlContext.get());
1188 return Handle(OpenGl_ShaderObject)();
1191 if (!aShader->LoadAndCompile (theGlContext, "", theSource.Source()))
1193 aShader->Release (theGlContext.get());
1194 return Handle(OpenGl_ShaderObject)();
1199 // =======================================================================
1200 // function : initProgram
1201 // purpose : Creates GLSL program from the given shader objects
1202 // =======================================================================
1203 Handle(OpenGl_ShaderProgram) OpenGl_View::initProgram (const Handle(OpenGl_Context)& theGlContext,
1204 const Handle(OpenGl_ShaderObject)& theVertShader,
1205 const Handle(OpenGl_ShaderObject)& theFragShader,
1206 const TCollection_AsciiString& theName)
1208 const TCollection_AsciiString anId = TCollection_AsciiString("occt_rt_") + theName;
1209 Handle(OpenGl_ShaderProgram) aProgram = new OpenGl_ShaderProgram(Handle(Graphic3d_ShaderProgram)(), anId);
1211 if (!aProgram->Create (theGlContext))
1213 theVertShader->Release (theGlContext.operator->());
1215 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1216 GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, "Failed to create shader program");
1218 return Handle(OpenGl_ShaderProgram)();
1221 if (!aProgram->AttachShader (theGlContext, theVertShader)
1222 || !aProgram->AttachShader (theGlContext, theFragShader))
1224 theVertShader->Release (theGlContext.operator->());
1226 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1227 GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, "Failed to attach shader objects");
1229 return Handle(OpenGl_ShaderProgram)();
1232 aProgram->SetAttributeName (theGlContext, Graphic3d_TOA_POS, "occVertex");
1234 TCollection_AsciiString aLinkLog;
1236 if (!aProgram->Link (theGlContext))
1238 aProgram->FetchInfoLog (theGlContext, aLinkLog);
1240 const TCollection_ExtendedString aMessage = TCollection_ExtendedString (
1241 "Failed to link shader program:\n") + aLinkLog;
1243 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1244 GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, aMessage);
1246 return Handle(OpenGl_ShaderProgram)();
1248 else if (theGlContext->caps->glslWarnings)
1250 aProgram->FetchInfoLog (theGlContext, aLinkLog);
1251 if (!aLinkLog.IsEmpty() && !aLinkLog.IsEqual ("No errors.\n"))
1253 const TCollection_ExtendedString aMessage = TCollection_ExtendedString (
1254 "Shader program was linked with following warnings:\n") + aLinkLog;
1256 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1257 GL_DEBUG_TYPE_PORTABILITY, 0, GL_DEBUG_SEVERITY_LOW, aMessage);
1264 // =======================================================================
1265 // function : initRaytraceResources
1266 // purpose : Initializes OpenGL/GLSL shader programs
1267 // =======================================================================
1268 Standard_Boolean OpenGl_View::initRaytraceResources (const Standard_Integer theSizeX,
1269 const Standard_Integer theSizeY,
1270 const Handle(OpenGl_Context)& theGlContext)
1272 if (myRaytraceInitStatus == OpenGl_RT_FAIL)
1274 return Standard_False;
1277 Standard_Boolean aToRebuildShaders = Standard_False;
1279 if (myRenderParams.RebuildRayTracingShaders) // requires complete re-initialization
1281 myRaytraceInitStatus = OpenGl_RT_NONE;
1282 releaseRaytraceResources (theGlContext, Standard_True);
1283 myRenderParams.RebuildRayTracingShaders = Standard_False; // clear rebuilding flag
1286 if (myRaytraceInitStatus == OpenGl_RT_INIT)
1288 if (!myIsRaytraceDataValid)
1290 return Standard_True;
1293 const Standard_Integer aRequiredStackSize =
1294 myRaytraceGeometry.TopLevelTreeDepth() + myRaytraceGeometry.BotLevelTreeDepth();
1296 if (myRaytraceParameters.StackSize < aRequiredStackSize)
1298 myRaytraceParameters.StackSize = Max (aRequiredStackSize, THE_DEFAULT_STACK_SIZE);
1300 aToRebuildShaders = Standard_True;
1304 if (aRequiredStackSize < myRaytraceParameters.StackSize)
1306 if (myRaytraceParameters.StackSize > THE_DEFAULT_STACK_SIZE)
1308 myRaytraceParameters.StackSize = Max (aRequiredStackSize, THE_DEFAULT_STACK_SIZE);
1309 aToRebuildShaders = Standard_True;
1314 if (myRenderParams.RaytracingDepth != myRaytraceParameters.NbBounces
1315 || myRenderParams.IsTransparentShadowEnabled != myRaytraceParameters.TransparentShadows
1316 || myRenderParams.IsGlobalIlluminationEnabled != myRaytraceParameters.GlobalIllumination
1317 || myRenderParams.TwoSidedBsdfModels != myRaytraceParameters.TwoSidedBsdfModels
1318 || myRaytraceGeometry.HasTextures() != myRaytraceParameters.UseBindlessTextures)
1320 myRaytraceParameters.NbBounces = myRenderParams.RaytracingDepth;
1321 myRaytraceParameters.TransparentShadows = myRenderParams.IsTransparentShadowEnabled;
1322 myRaytraceParameters.GlobalIllumination = myRenderParams.IsGlobalIlluminationEnabled;
1323 myRaytraceParameters.TwoSidedBsdfModels = myRenderParams.TwoSidedBsdfModels;
1324 myRaytraceParameters.UseBindlessTextures = myRaytraceGeometry.HasTextures();
1325 aToRebuildShaders = Standard_True;
1328 if (myRenderParams.AdaptiveScreenSampling != myRaytraceParameters.AdaptiveScreenSampling
1329 || myRenderParams.AdaptiveScreenSamplingAtomic != myRaytraceParameters.AdaptiveScreenSamplingAtomic)
1331 myRaytraceParameters.AdaptiveScreenSampling = myRenderParams.AdaptiveScreenSampling;
1332 myRaytraceParameters.AdaptiveScreenSamplingAtomic = myRenderParams.AdaptiveScreenSamplingAtomic;
1333 if (myRenderParams.AdaptiveScreenSampling) // adaptive sampling was requested
1335 if (!theGlContext->HasRayTracingAdaptiveSampling())
1337 // disable the feature if it is not supported
1338 myRaytraceParameters.AdaptiveScreenSampling = myRenderParams.AdaptiveScreenSampling = Standard_False;
1339 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_PORTABILITY, 0, GL_DEBUG_SEVERITY_LOW,
1340 "Adaptive sampling is not supported (OpenGL 4.4 is missing)");
1342 else if (myRaytraceParameters.AdaptiveScreenSamplingAtomic
1343 && !theGlContext->HasRayTracingAdaptiveSamplingAtomic())
1345 // disable the feature if it is not supported
1346 myRaytraceParameters.AdaptiveScreenSamplingAtomic = myRenderParams.AdaptiveScreenSamplingAtomic = Standard_False;
1347 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_PORTABILITY, 0, GL_DEBUG_SEVERITY_LOW,
1348 "Atomic adaptive sampling is not supported (GL_NV_shader_atomic_float is missing)");
1352 aToRebuildShaders = Standard_True;
1354 myTileSampler.SetSize (myRenderParams, myRaytraceParameters.AdaptiveScreenSampling ? Graphic3d_Vec2i (theSizeX, theSizeY) : Graphic3d_Vec2i (0, 0));
1356 const bool toEnableDof = !myCamera->IsOrthographic() && myRaytraceParameters.GlobalIllumination;
1357 if (myRaytraceParameters.DepthOfField != toEnableDof)
1359 myRaytraceParameters.DepthOfField = toEnableDof;
1360 aToRebuildShaders = Standard_True;
1363 if (myRenderParams.ToneMappingMethod != myRaytraceParameters.ToneMappingMethod)
1365 myRaytraceParameters.ToneMappingMethod = myRenderParams.ToneMappingMethod;
1366 aToRebuildShaders = true;
1369 if (aToRebuildShaders)
1371 // Reject accumulated frames
1374 // Environment map should be updated
1375 myToUpdateEnvironmentMap = Standard_True;
1377 const TCollection_AsciiString aPrefixString = generateShaderPrefix (theGlContext);
1379 #ifdef RAY_TRACE_PRINT_INFO
1380 std::cout << "GLSL prefix string:" << std::endl << aPrefixString << std::endl;
1383 myRaytraceShaderSource.SetPrefix (aPrefixString);
1384 myPostFSAAShaderSource.SetPrefix (aPrefixString);
1385 myOutImageShaderSource.SetPrefix (aPrefixString);
1387 if (!myRaytraceShader->LoadAndCompile (theGlContext, myRaytraceProgram->ResourceId(), myRaytraceShaderSource.Source())
1388 || !myPostFSAAShader->LoadAndCompile (theGlContext, myPostFSAAProgram->ResourceId(), myPostFSAAShaderSource.Source())
1389 || !myOutImageShader->LoadAndCompile (theGlContext, myOutImageProgram->ResourceId(), myOutImageShaderSource.Source()))
1391 return safeFailBack ("Failed to compile ray-tracing fragment shaders", theGlContext);
1394 myRaytraceProgram->SetAttributeName (theGlContext, Graphic3d_TOA_POS, "occVertex");
1395 myPostFSAAProgram->SetAttributeName (theGlContext, Graphic3d_TOA_POS, "occVertex");
1396 myOutImageProgram->SetAttributeName (theGlContext, Graphic3d_TOA_POS, "occVertex");
1398 if (!myRaytraceProgram->Link (theGlContext)
1399 || !myPostFSAAProgram->Link (theGlContext)
1400 || !myOutImageProgram->Link (theGlContext))
1402 return safeFailBack ("Failed to initialize vertex attributes for ray-tracing program", theGlContext);
1407 if (myRaytraceInitStatus == OpenGl_RT_NONE)
1409 myAccumFrames = 0; // accumulation should be restarted
1411 if (!theGlContext->IsGlGreaterEqual (3, 1))
1413 return safeFailBack ("Ray-tracing requires OpenGL 3.1 and higher", theGlContext);
1415 else if (!theGlContext->arbTboRGB32)
1417 return safeFailBack ("Ray-tracing requires OpenGL 4.0+ or GL_ARB_texture_buffer_object_rgb32 extension", theGlContext);
1419 else if (!theGlContext->arbFBOBlit)
1421 return safeFailBack ("Ray-tracing requires EXT_framebuffer_blit extension", theGlContext);
1424 myRaytraceParameters.NbBounces = myRenderParams.RaytracingDepth;
1426 const TCollection_AsciiString aShaderFolder = Graphic3d_ShaderProgram::ShadersFolder();
1427 if (myIsRaytraceDataValid)
1429 myRaytraceParameters.StackSize = Max (THE_DEFAULT_STACK_SIZE,
1430 myRaytraceGeometry.TopLevelTreeDepth() + myRaytraceGeometry.BotLevelTreeDepth());
1433 const TCollection_AsciiString aPrefixString = generateShaderPrefix (theGlContext);
1435 #ifdef RAY_TRACE_PRINT_INFO
1436 std::cout << "GLSL prefix string:" << std::endl << aPrefixString << std::endl;
1439 ShaderSource aBasicVertShaderSrc;
1441 if (!aShaderFolder.IsEmpty())
1443 const TCollection_AsciiString aFiles[] = { aShaderFolder + "/RaytraceBase.vs", "" };
1444 if (!aBasicVertShaderSrc.LoadFromFiles (aFiles))
1446 return safeFailBack (aBasicVertShaderSrc.ErrorDescription(), theGlContext);
1451 const TCollection_AsciiString aSrcShaders[] = { Shaders_RaytraceBase_vs, "" };
1452 aBasicVertShaderSrc.LoadFromStrings (aSrcShaders);
1457 if (!aShaderFolder.IsEmpty())
1459 const TCollection_AsciiString aFiles[] = { aShaderFolder + "/RaytraceBase.fs",
1460 aShaderFolder + "/PathtraceBase.fs",
1461 aShaderFolder + "/RaytraceRender.fs",
1463 if (!myRaytraceShaderSource.LoadFromFiles (aFiles, aPrefixString))
1465 return safeFailBack (myRaytraceShaderSource.ErrorDescription(), theGlContext);
1470 const TCollection_AsciiString aSrcShaders[] = { Shaders_RaytraceBase_fs,
1471 Shaders_PathtraceBase_fs,
1472 Shaders_RaytraceRender_fs,
1474 myRaytraceShaderSource.LoadFromStrings (aSrcShaders, aPrefixString);
1477 Handle(OpenGl_ShaderObject) aBasicVertShader = initShader (GL_VERTEX_SHADER, aBasicVertShaderSrc, theGlContext);
1478 if (aBasicVertShader.IsNull())
1480 return safeFailBack ("Failed to initialize ray-trace vertex shader", theGlContext);
1483 myRaytraceShader = initShader (GL_FRAGMENT_SHADER, myRaytraceShaderSource, theGlContext);
1484 if (myRaytraceShader.IsNull())
1486 aBasicVertShader->Release (theGlContext.operator->());
1487 return safeFailBack ("Failed to initialize ray-trace fragment shader", theGlContext);
1490 myRaytraceProgram = initProgram (theGlContext, aBasicVertShader, myRaytraceShader, "main");
1491 if (myRaytraceProgram.IsNull())
1493 return safeFailBack ("Failed to initialize ray-trace shader program", theGlContext);
1498 if (!aShaderFolder.IsEmpty())
1500 const TCollection_AsciiString aFiles[] = { aShaderFolder + "/RaytraceBase.fs", aShaderFolder + "/RaytraceSmooth.fs", "" };
1501 if (!myPostFSAAShaderSource.LoadFromFiles (aFiles, aPrefixString))
1503 return safeFailBack (myPostFSAAShaderSource.ErrorDescription(), theGlContext);
1508 const TCollection_AsciiString aSrcShaders[] = { Shaders_RaytraceBase_fs, Shaders_RaytraceSmooth_fs, "" };
1509 myPostFSAAShaderSource.LoadFromStrings (aSrcShaders, aPrefixString);
1512 Handle(OpenGl_ShaderObject) aBasicVertShader = initShader (GL_VERTEX_SHADER, aBasicVertShaderSrc, theGlContext);
1513 if (aBasicVertShader.IsNull())
1515 return safeFailBack ("Failed to initialize FSAA vertex shader", theGlContext);
1518 myPostFSAAShader = initShader (GL_FRAGMENT_SHADER, myPostFSAAShaderSource, theGlContext);
1519 if (myPostFSAAShader.IsNull())
1521 aBasicVertShader->Release (theGlContext.operator->());
1522 return safeFailBack ("Failed to initialize FSAA fragment shader", theGlContext);
1525 myPostFSAAProgram = initProgram (theGlContext, aBasicVertShader, myPostFSAAShader, "fsaa");
1526 if (myPostFSAAProgram.IsNull())
1528 return safeFailBack ("Failed to initialize FSAA shader program", theGlContext);
1533 if (!aShaderFolder.IsEmpty())
1535 const TCollection_AsciiString aFiles[] = { aShaderFolder + "/Display.fs", "" };
1536 if (!myOutImageShaderSource.LoadFromFiles (aFiles, aPrefixString))
1538 return safeFailBack (myOutImageShaderSource.ErrorDescription(), theGlContext);
1543 const TCollection_AsciiString aSrcShaders[] = { Shaders_Display_fs, "" };
1544 myOutImageShaderSource.LoadFromStrings (aSrcShaders, aPrefixString);
1547 Handle(OpenGl_ShaderObject) aBasicVertShader = initShader (GL_VERTEX_SHADER, aBasicVertShaderSrc, theGlContext);
1548 if (aBasicVertShader.IsNull())
1550 return safeFailBack ("Failed to set vertex shader source", theGlContext);
1553 myOutImageShader = initShader (GL_FRAGMENT_SHADER, myOutImageShaderSource, theGlContext);
1554 if (myOutImageShader.IsNull())
1556 aBasicVertShader->Release (theGlContext.operator->());
1557 return safeFailBack ("Failed to set display fragment shader source", theGlContext);
1560 myOutImageProgram = initProgram (theGlContext, aBasicVertShader, myOutImageShader, "out");
1561 if (myOutImageProgram.IsNull())
1563 return safeFailBack ("Failed to initialize display shader program", theGlContext);
1568 if (myRaytraceInitStatus == OpenGl_RT_NONE || aToRebuildShaders)
1570 for (Standard_Integer anIndex = 0; anIndex < 2; ++anIndex)
1572 Handle(OpenGl_ShaderProgram)& aShaderProgram =
1573 (anIndex == 0) ? myRaytraceProgram : myPostFSAAProgram;
1575 theGlContext->BindProgram (aShaderProgram);
1577 aShaderProgram->SetSampler (theGlContext,
1578 "uSceneMinPointTexture", OpenGl_RT_SceneMinPointTexture);
1579 aShaderProgram->SetSampler (theGlContext,
1580 "uSceneMaxPointTexture", OpenGl_RT_SceneMaxPointTexture);
1581 aShaderProgram->SetSampler (theGlContext,
1582 "uSceneNodeInfoTexture", OpenGl_RT_SceneNodeInfoTexture);
1583 aShaderProgram->SetSampler (theGlContext,
1584 "uGeometryVertexTexture", OpenGl_RT_GeometryVertexTexture);
1585 aShaderProgram->SetSampler (theGlContext,
1586 "uGeometryNormalTexture", OpenGl_RT_GeometryNormalTexture);
1587 aShaderProgram->SetSampler (theGlContext,
1588 "uGeometryTexCrdTexture", OpenGl_RT_GeometryTexCrdTexture);
1589 aShaderProgram->SetSampler (theGlContext,
1590 "uGeometryTriangTexture", OpenGl_RT_GeometryTriangTexture);
1591 aShaderProgram->SetSampler (theGlContext,
1592 "uSceneTransformTexture", OpenGl_RT_SceneTransformTexture);
1593 aShaderProgram->SetSampler (theGlContext,
1594 "uEnvironmentMapTexture", OpenGl_RT_EnvironmentMapTexture);
1595 aShaderProgram->SetSampler (theGlContext,
1596 "uRaytraceMaterialTexture", OpenGl_RT_RaytraceMaterialTexture);
1597 aShaderProgram->SetSampler (theGlContext,
1598 "uRaytraceLightSrcTexture", OpenGl_RT_RaytraceLightSrcTexture);
1602 aShaderProgram->SetSampler (theGlContext,
1603 "uFSAAInputTexture", OpenGl_RT_FsaaInputTexture);
1607 aShaderProgram->SetSampler (theGlContext,
1608 "uAccumTexture", OpenGl_RT_PrevAccumTexture);
1611 myUniformLocations[anIndex][OpenGl_RT_aPosition] =
1612 aShaderProgram->GetAttributeLocation (theGlContext, "occVertex");
1614 myUniformLocations[anIndex][OpenGl_RT_uOriginLB] =
1615 aShaderProgram->GetUniformLocation (theGlContext, "uOriginLB");
1616 myUniformLocations[anIndex][OpenGl_RT_uOriginRB] =
1617 aShaderProgram->GetUniformLocation (theGlContext, "uOriginRB");
1618 myUniformLocations[anIndex][OpenGl_RT_uOriginLT] =
1619 aShaderProgram->GetUniformLocation (theGlContext, "uOriginLT");
1620 myUniformLocations[anIndex][OpenGl_RT_uOriginRT] =
1621 aShaderProgram->GetUniformLocation (theGlContext, "uOriginRT");
1622 myUniformLocations[anIndex][OpenGl_RT_uDirectLB] =
1623 aShaderProgram->GetUniformLocation (theGlContext, "uDirectLB");
1624 myUniformLocations[anIndex][OpenGl_RT_uDirectRB] =
1625 aShaderProgram->GetUniformLocation (theGlContext, "uDirectRB");
1626 myUniformLocations[anIndex][OpenGl_RT_uDirectLT] =
1627 aShaderProgram->GetUniformLocation (theGlContext, "uDirectLT");
1628 myUniformLocations[anIndex][OpenGl_RT_uDirectRT] =
1629 aShaderProgram->GetUniformLocation (theGlContext, "uDirectRT");
1630 myUniformLocations[anIndex][OpenGl_RT_uViewPrMat] =
1631 aShaderProgram->GetUniformLocation (theGlContext, "uViewMat");
1632 myUniformLocations[anIndex][OpenGl_RT_uUnviewMat] =
1633 aShaderProgram->GetUniformLocation (theGlContext, "uUnviewMat");
1635 myUniformLocations[anIndex][OpenGl_RT_uSceneRad] =
1636 aShaderProgram->GetUniformLocation (theGlContext, "uSceneRadius");
1637 myUniformLocations[anIndex][OpenGl_RT_uSceneEps] =
1638 aShaderProgram->GetUniformLocation (theGlContext, "uSceneEpsilon");
1639 myUniformLocations[anIndex][OpenGl_RT_uLightCount] =
1640 aShaderProgram->GetUniformLocation (theGlContext, "uLightCount");
1641 myUniformLocations[anIndex][OpenGl_RT_uLightAmbnt] =
1642 aShaderProgram->GetUniformLocation (theGlContext, "uGlobalAmbient");
1644 myUniformLocations[anIndex][OpenGl_RT_uOffsetX] =
1645 aShaderProgram->GetUniformLocation (theGlContext, "uOffsetX");
1646 myUniformLocations[anIndex][OpenGl_RT_uOffsetY] =
1647 aShaderProgram->GetUniformLocation (theGlContext, "uOffsetY");
1648 myUniformLocations[anIndex][OpenGl_RT_uSamples] =
1649 aShaderProgram->GetUniformLocation (theGlContext, "uSamples");
1651 myUniformLocations[anIndex][OpenGl_RT_uTexSamplersArray] =
1652 aShaderProgram->GetUniformLocation (theGlContext, "uTextureSamplers");
1654 myUniformLocations[anIndex][OpenGl_RT_uShadowsEnabled] =
1655 aShaderProgram->GetUniformLocation (theGlContext, "uShadowsEnabled");
1656 myUniformLocations[anIndex][OpenGl_RT_uReflectEnabled] =
1657 aShaderProgram->GetUniformLocation (theGlContext, "uReflectEnabled");
1658 myUniformLocations[anIndex][OpenGl_RT_uSphereMapEnabled] =
1659 aShaderProgram->GetUniformLocation (theGlContext, "uSphereMapEnabled");
1660 myUniformLocations[anIndex][OpenGl_RT_uSphereMapForBack] =
1661 aShaderProgram->GetUniformLocation (theGlContext, "uSphereMapForBack");
1662 myUniformLocations[anIndex][OpenGl_RT_uBlockedRngEnabled] =
1663 aShaderProgram->GetUniformLocation (theGlContext, "uBlockedRngEnabled");
1665 myUniformLocations[anIndex][OpenGl_RT_uWinSizeX] =
1666 aShaderProgram->GetUniformLocation (theGlContext, "uWinSizeX");
1667 myUniformLocations[anIndex][OpenGl_RT_uWinSizeY] =
1668 aShaderProgram->GetUniformLocation (theGlContext, "uWinSizeY");
1670 myUniformLocations[anIndex][OpenGl_RT_uAccumSamples] =
1671 aShaderProgram->GetUniformLocation (theGlContext, "uAccumSamples");
1672 myUniformLocations[anIndex][OpenGl_RT_uFrameRndSeed] =
1673 aShaderProgram->GetUniformLocation (theGlContext, "uFrameRndSeed");
1675 myUniformLocations[anIndex][OpenGl_RT_uRenderImage] =
1676 aShaderProgram->GetUniformLocation (theGlContext, "uRenderImage");
1677 myUniformLocations[anIndex][OpenGl_RT_uTilesImage] =
1678 aShaderProgram->GetUniformLocation (theGlContext, "uTilesImage");
1679 myUniformLocations[anIndex][OpenGl_RT_uOffsetImage] =
1680 aShaderProgram->GetUniformLocation (theGlContext, "uOffsetImage");
1681 myUniformLocations[anIndex][OpenGl_RT_uTileSize] =
1682 aShaderProgram->GetUniformLocation (theGlContext, "uTileSize");
1683 myUniformLocations[anIndex][OpenGl_RT_uVarianceScaleFactor] =
1684 aShaderProgram->GetUniformLocation (theGlContext, "uVarianceScaleFactor");
1686 myUniformLocations[anIndex][OpenGl_RT_uBackColorTop] =
1687 aShaderProgram->GetUniformLocation (theGlContext, "uBackColorTop");
1688 myUniformLocations[anIndex][OpenGl_RT_uBackColorBot] =
1689 aShaderProgram->GetUniformLocation (theGlContext, "uBackColorBot");
1691 myUniformLocations[anIndex][OpenGl_RT_uMaxRadiance] =
1692 aShaderProgram->GetUniformLocation (theGlContext, "uMaxRadiance");
1695 theGlContext->BindProgram (myOutImageProgram);
1697 myOutImageProgram->SetSampler (theGlContext,
1698 "uInputTexture", OpenGl_RT_PrevAccumTexture);
1700 myOutImageProgram->SetSampler (theGlContext,
1701 "uDepthTexture", OpenGl_RT_RaytraceDepthTexture);
1703 theGlContext->BindProgram (NULL);
1706 if (myRaytraceInitStatus != OpenGl_RT_NONE)
1708 return myRaytraceInitStatus == OpenGl_RT_INIT;
1711 const GLfloat aVertices[] = { -1.f, -1.f, 0.f,
1718 myRaytraceScreenQuad.Init (theGlContext, 3, 6, aVertices);
1720 myRaytraceInitStatus = OpenGl_RT_INIT; // initialized in normal way
1722 return Standard_True;
1725 // =======================================================================
1726 // function : nullifyResource
1727 // purpose : Releases OpenGL resource
1728 // =======================================================================
1730 inline void nullifyResource (const Handle(OpenGl_Context)& theGlContext, Handle(T)& theResource)
1732 if (!theResource.IsNull())
1734 theResource->Release (theGlContext.get());
1735 theResource.Nullify();
1739 // =======================================================================
1740 // function : releaseRaytraceResources
1741 // purpose : Releases OpenGL/GLSL shader programs
1742 // =======================================================================
1743 void OpenGl_View::releaseRaytraceResources (const Handle(OpenGl_Context)& theGlContext, const Standard_Boolean theToRebuild)
1745 // release shader resources
1746 nullifyResource (theGlContext, myRaytraceShader);
1747 nullifyResource (theGlContext, myPostFSAAShader);
1749 nullifyResource (theGlContext, myRaytraceProgram);
1750 nullifyResource (theGlContext, myPostFSAAProgram);
1751 nullifyResource (theGlContext, myOutImageProgram);
1753 if (!theToRebuild) // complete release
1755 myRaytraceFBO1[0]->Release (theGlContext.get());
1756 myRaytraceFBO1[1]->Release (theGlContext.get());
1757 myRaytraceFBO2[0]->Release (theGlContext.get());
1758 myRaytraceFBO2[1]->Release (theGlContext.get());
1760 nullifyResource (theGlContext, myRaytraceOutputTexture[0]);
1761 nullifyResource (theGlContext, myRaytraceOutputTexture[1]);
1763 nullifyResource (theGlContext, myRaytraceTileOffsetsTexture[0]);
1764 nullifyResource (theGlContext, myRaytraceTileOffsetsTexture[1]);
1765 nullifyResource (theGlContext, myRaytraceVisualErrorTexture[0]);
1766 nullifyResource (theGlContext, myRaytraceVisualErrorTexture[1]);
1767 nullifyResource (theGlContext, myRaytraceTileSamplesTexture[0]);
1768 nullifyResource (theGlContext, myRaytraceTileSamplesTexture[1]);
1770 nullifyResource (theGlContext, mySceneNodeInfoTexture);
1771 nullifyResource (theGlContext, mySceneMinPointTexture);
1772 nullifyResource (theGlContext, mySceneMaxPointTexture);
1774 nullifyResource (theGlContext, myGeometryVertexTexture);
1775 nullifyResource (theGlContext, myGeometryNormalTexture);
1776 nullifyResource (theGlContext, myGeometryTexCrdTexture);
1777 nullifyResource (theGlContext, myGeometryTriangTexture);
1778 nullifyResource (theGlContext, mySceneTransformTexture);
1780 nullifyResource (theGlContext, myRaytraceLightSrcTexture);
1781 nullifyResource (theGlContext, myRaytraceMaterialTexture);
1783 myRaytraceGeometry.ReleaseResources (theGlContext);
1785 if (myRaytraceScreenQuad.IsValid ())
1787 myRaytraceScreenQuad.Release (theGlContext.get());
1792 // =======================================================================
1793 // function : updateRaytraceBuffers
1794 // purpose : Updates auxiliary OpenGL frame buffers.
1795 // =======================================================================
1796 Standard_Boolean OpenGl_View::updateRaytraceBuffers (const Standard_Integer theSizeX,
1797 const Standard_Integer theSizeY,
1798 const Handle(OpenGl_Context)& theGlContext)
1800 // Auxiliary buffers are not used
1801 if (!myRaytraceParameters.GlobalIllumination && !myRenderParams.IsAntialiasingEnabled)
1803 myRaytraceFBO1[0]->Release (theGlContext.operator->());
1804 myRaytraceFBO2[0]->Release (theGlContext.operator->());
1805 myRaytraceFBO1[1]->Release (theGlContext.operator->());
1806 myRaytraceFBO2[1]->Release (theGlContext.operator->());
1808 return Standard_True;
1811 if (myRaytraceParameters.AdaptiveScreenSampling)
1813 Graphic3d_Vec2i aMaxViewport = myTileSampler.OffsetTilesViewportMax().cwiseMax (Graphic3d_Vec2i (theSizeX, theSizeY));
1814 myRaytraceFBO1[0]->InitLazy (theGlContext, aMaxViewport.x(), aMaxViewport.y(), GL_RGBA32F, myFboDepthFormat);
1815 myRaytraceFBO2[0]->InitLazy (theGlContext, aMaxViewport.x(), aMaxViewport.y(), GL_RGBA32F, myFboDepthFormat);
1816 if (myRaytraceFBO1[1]->IsValid()) // second FBO not needed
1818 myRaytraceFBO1[1]->Release (theGlContext.operator->());
1819 myRaytraceFBO2[1]->Release (theGlContext.operator->());
1823 for (int aViewIter = 0; aViewIter < 2; ++aViewIter)
1825 if (myRaytraceTileOffsetsTexture[aViewIter].IsNull())
1827 myRaytraceOutputTexture[aViewIter] = new OpenGl_Texture();
1828 myRaytraceVisualErrorTexture[aViewIter] = new OpenGl_Texture();
1829 myRaytraceTileSamplesTexture[aViewIter] = new OpenGl_Texture();
1830 myRaytraceTileOffsetsTexture[aViewIter] = new OpenGl_Texture();
1834 && myCamera->ProjectionType() != Graphic3d_Camera::Projection_Stereo)
1836 myRaytraceFBO1[1]->Release (theGlContext.operator->());
1837 myRaytraceFBO2[1]->Release (theGlContext.operator->());
1838 myRaytraceOutputTexture[1]->Release (theGlContext.operator->());
1839 myRaytraceVisualErrorTexture[1]->Release (theGlContext.operator->());
1840 myRaytraceTileOffsetsTexture[1]->Release (theGlContext.operator->());
1844 if (myRaytraceParameters.AdaptiveScreenSampling)
1846 if (myRaytraceOutputTexture[aViewIter]->SizeX() / 3 == theSizeX
1847 && myRaytraceOutputTexture[aViewIter]->SizeY() / 2 == theSizeY
1848 && myRaytraceVisualErrorTexture[aViewIter]->SizeX() == myTileSampler.NbTilesX()
1849 && myRaytraceVisualErrorTexture[aViewIter]->SizeY() == myTileSampler.NbTilesY())
1851 if (myRaytraceParameters.AdaptiveScreenSamplingAtomic)
1853 continue; // offsets texture is dynamically resized
1855 else if (myRaytraceTileSamplesTexture[aViewIter]->SizeX() == myTileSampler.NbTilesX()
1856 && myRaytraceTileSamplesTexture[aViewIter]->SizeY() == myTileSampler.NbTilesY())
1864 // Due to limitations of OpenGL image load-store extension
1865 // atomic operations are supported only for single-channel
1866 // images, so we define GL_R32F image. It is used as array
1867 // of 6D floating point vectors:
1868 // 0 - R color channel
1869 // 1 - G color channel
1870 // 2 - B color channel
1871 // 3 - hit time transformed into OpenGL NDC space
1872 // 4 - luminance accumulated for odd samples only
1873 myRaytraceOutputTexture[aViewIter]->InitRectangle (theGlContext, theSizeX * 3, theSizeY * 2, OpenGl_TextureFormat::Create<GLfloat, 1>());
1875 // workaround for some NVIDIA drivers
1876 myRaytraceVisualErrorTexture[aViewIter]->Release (theGlContext.operator->());
1877 myRaytraceTileSamplesTexture[aViewIter]->Release (theGlContext.operator->());
1878 myRaytraceVisualErrorTexture[aViewIter]->Init (theGlContext,
1879 OpenGl_TextureFormat::FindSizedFormat (theGlContext, GL_R32I),
1880 Graphic3d_Vec2i (myTileSampler.NbTilesX(), myTileSampler.NbTilesY()),
1882 if (!myRaytraceParameters.AdaptiveScreenSamplingAtomic)
1884 myRaytraceTileSamplesTexture[aViewIter]->Init (theGlContext,
1885 OpenGl_TextureFormat::FindSizedFormat (theGlContext, GL_R32I),
1886 Graphic3d_Vec2i (myTileSampler.NbTilesX(), myTileSampler.NbTilesY()),
1890 else // non-adaptive mode
1892 if (myRaytraceFBO1[aViewIter]->GetSizeX() != theSizeX
1893 || myRaytraceFBO1[aViewIter]->GetSizeY() != theSizeY)
1895 myAccumFrames = 0; // accumulation should be restarted
1898 myRaytraceFBO1[aViewIter]->InitLazy (theGlContext, theSizeX, theSizeY, GL_RGBA32F, myFboDepthFormat);
1899 myRaytraceFBO2[aViewIter]->InitLazy (theGlContext, theSizeX, theSizeY, GL_RGBA32F, myFboDepthFormat);
1902 return Standard_True;
1905 // =======================================================================
1906 // function : updateCamera
1907 // purpose : Generates viewing rays for corners of screen quad
1908 // =======================================================================
1909 void OpenGl_View::updateCamera (const OpenGl_Mat4& theOrientation,
1910 const OpenGl_Mat4& theViewMapping,
1911 OpenGl_Vec3* theOrigins,
1912 OpenGl_Vec3* theDirects,
1913 OpenGl_Mat4& theViewPr,
1914 OpenGl_Mat4& theUnview)
1916 // compute view-projection matrix
1917 theViewPr = theViewMapping * theOrientation;
1919 // compute inverse view-projection matrix
1920 theViewPr.Inverted (theUnview);
1922 Standard_Integer aOriginIndex = 0;
1923 Standard_Integer aDirectIndex = 0;
1925 for (Standard_Integer aY = -1; aY <= 1; aY += 2)
1927 for (Standard_Integer aX = -1; aX <= 1; aX += 2)
1929 OpenGl_Vec4 aOrigin (GLfloat(aX),
1934 aOrigin = theUnview * aOrigin;
1936 aOrigin.x() = aOrigin.x() / aOrigin.w();
1937 aOrigin.y() = aOrigin.y() / aOrigin.w();
1938 aOrigin.z() = aOrigin.z() / aOrigin.w();
1940 OpenGl_Vec4 aDirect (GLfloat(aX),
1945 aDirect = theUnview * aDirect;
1947 aDirect.x() = aDirect.x() / aDirect.w();
1948 aDirect.y() = aDirect.y() / aDirect.w();
1949 aDirect.z() = aDirect.z() / aDirect.w();
1951 aDirect = aDirect - aOrigin;
1953 theOrigins[aOriginIndex++] = OpenGl_Vec3 (static_cast<GLfloat> (aOrigin.x()),
1954 static_cast<GLfloat> (aOrigin.y()),
1955 static_cast<GLfloat> (aOrigin.z()));
1957 theDirects[aDirectIndex++] = OpenGl_Vec3 (static_cast<GLfloat> (aDirect.x()),
1958 static_cast<GLfloat> (aDirect.y()),
1959 static_cast<GLfloat> (aDirect.z()));
1964 // =======================================================================
1965 // function : updatePerspCameraPT
1966 // purpose : Generates viewing rays (path tracing, perspective camera)
1967 // =======================================================================
1968 void OpenGl_View::updatePerspCameraPT (const OpenGl_Mat4& theOrientation,
1969 const OpenGl_Mat4& theViewMapping,
1970 Graphic3d_Camera::Projection theProjection,
1971 OpenGl_Mat4& theViewPr,
1972 OpenGl_Mat4& theUnview,
1973 const int theWinSizeX,
1974 const int theWinSizeY)
1976 // compute view-projection matrix
1977 theViewPr = theViewMapping * theOrientation;
1979 // compute inverse view-projection matrix
1980 theViewPr.Inverted(theUnview);
1982 // get camera stereo params
1983 float anIOD = myCamera->GetIODType() == Graphic3d_Camera::IODType_Relative
1984 ? static_cast<float> (myCamera->IOD() * myCamera->Distance())
1985 : static_cast<float> (myCamera->IOD());
1987 float aZFocus = myCamera->ZFocusType() == Graphic3d_Camera::FocusType_Relative
1988 ? static_cast<float> (myCamera->ZFocus() * myCamera->Distance())
1989 : static_cast<float> (myCamera->ZFocus());
1991 // get camera view vectors
1992 const gp_Pnt anOrig = myCamera->Eye();
1994 myEyeOrig = OpenGl_Vec3 (static_cast<float> (anOrig.X()),
1995 static_cast<float> (anOrig.Y()),
1996 static_cast<float> (anOrig.Z()));
1998 const gp_Dir aView = myCamera->Direction();
2000 OpenGl_Vec3 anEyeViewMono = OpenGl_Vec3 (static_cast<float> (aView.X()),
2001 static_cast<float> (aView.Y()),
2002 static_cast<float> (aView.Z()));
2004 const gp_Dir anUp = myCamera->Up();
2006 myEyeVert = OpenGl_Vec3 (static_cast<float> (anUp.X()),
2007 static_cast<float> (anUp.Y()),
2008 static_cast<float> (anUp.Z()));
2010 myEyeSide = OpenGl_Vec3::Cross (anEyeViewMono, myEyeVert);
2012 const double aScaleY = tan (myCamera->FOVy() / 360 * M_PI);
2013 const double aScaleX = theWinSizeX * aScaleY / theWinSizeY;
2015 myEyeSize = OpenGl_Vec2 (static_cast<float> (aScaleX),
2016 static_cast<float> (aScaleY));
2018 if (theProjection == Graphic3d_Camera::Projection_Perspective)
2020 myEyeView = anEyeViewMono;
2022 else // stereo camera
2024 // compute z-focus point
2025 OpenGl_Vec3 aZFocusPoint = myEyeOrig + anEyeViewMono * aZFocus;
2027 // compute stereo camera shift
2028 float aDx = theProjection == Graphic3d_Camera::Projection_MonoRightEye ? 0.5f * anIOD : -0.5f * anIOD;
2029 myEyeOrig += myEyeSide.Normalized() * aDx;
2031 // estimate new camera direction vector and correct its length
2032 myEyeView = (aZFocusPoint - myEyeOrig).Normalized();
2033 myEyeView *= 1.f / anEyeViewMono.Dot (myEyeView);
2037 // =======================================================================
2038 // function : uploadRaytraceData
2039 // purpose : Uploads ray-trace data to the GPU
2040 // =======================================================================
2041 Standard_Boolean OpenGl_View::uploadRaytraceData (const Handle(OpenGl_Context)& theGlContext)
2043 if (!theGlContext->IsGlGreaterEqual (3, 1))
2045 #ifdef RAY_TRACE_PRINT_INFO
2046 std::cout << "Error: OpenGL version is less than 3.1" << std::endl;
2048 return Standard_False;
2051 myAccumFrames = 0; // accumulation should be restarted
2053 /////////////////////////////////////////////////////////////////////////////
2054 // Prepare OpenGL textures
2056 if (theGlContext->arbTexBindless != NULL)
2058 // If OpenGL driver supports bindless textures we need
2059 // to get unique 64- bit handles for using on the GPU
2060 if (!myRaytraceGeometry.UpdateTextureHandles (theGlContext))
2062 #ifdef RAY_TRACE_PRINT_INFO
2063 std::cout << "Error: Failed to get OpenGL texture handles" << std::endl;
2065 return Standard_False;
2069 /////////////////////////////////////////////////////////////////////////////
2070 // Create OpenGL BVH buffers
2072 if (mySceneNodeInfoTexture.IsNull()) // create scene BVH buffers
2074 mySceneNodeInfoTexture = new OpenGl_TextureBufferArb;
2075 mySceneMinPointTexture = new OpenGl_TextureBufferArb;
2076 mySceneMaxPointTexture = new OpenGl_TextureBufferArb;
2077 mySceneTransformTexture = new OpenGl_TextureBufferArb;
2079 if (!mySceneNodeInfoTexture->Create (theGlContext)
2080 || !mySceneMinPointTexture->Create (theGlContext)
2081 || !mySceneMaxPointTexture->Create (theGlContext)
2082 || !mySceneTransformTexture->Create (theGlContext))
2084 #ifdef RAY_TRACE_PRINT_INFO
2085 std::cout << "Error: Failed to create scene BVH buffers" << std::endl;
2087 return Standard_False;
2091 if (myGeometryVertexTexture.IsNull()) // create geometry buffers
2093 myGeometryVertexTexture = new OpenGl_TextureBufferArb;
2094 myGeometryNormalTexture = new OpenGl_TextureBufferArb;
2095 myGeometryTexCrdTexture = new OpenGl_TextureBufferArb;
2096 myGeometryTriangTexture = new OpenGl_TextureBufferArb;
2098 if (!myGeometryVertexTexture->Create (theGlContext)
2099 || !myGeometryNormalTexture->Create (theGlContext)
2100 || !myGeometryTexCrdTexture->Create (theGlContext)
2101 || !myGeometryTriangTexture->Create (theGlContext))
2103 #ifdef RAY_TRACE_PRINT_INFO
2104 std::cout << "Error: Failed to create buffers for triangulation data" << std::endl;
2106 return Standard_False;
2110 if (myRaytraceMaterialTexture.IsNull()) // create material buffer
2112 myRaytraceMaterialTexture = new OpenGl_TextureBufferArb;
2114 if (!myRaytraceMaterialTexture->Create (theGlContext))
2116 #ifdef RAY_TRACE_PRINT_INFO
2117 std::cout << "Error: Failed to create buffers for material data" << std::endl;
2119 return Standard_False;
2123 /////////////////////////////////////////////////////////////////////////////
2124 // Write transform buffer
2126 BVH_Mat4f* aNodeTransforms = new BVH_Mat4f[myRaytraceGeometry.Size()];
2128 bool aResult = true;
2130 for (Standard_Integer anElemIndex = 0; anElemIndex < myRaytraceGeometry.Size(); ++anElemIndex)
2132 OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
2133 myRaytraceGeometry.Objects().ChangeValue (anElemIndex).operator->());
2135 const BVH_Transform<Standard_ShortReal, 4>* aTransform = dynamic_cast<const BVH_Transform<Standard_ShortReal, 4>* > (aTriangleSet->Properties().get());
2136 Standard_ASSERT_RETURN (aTransform != NULL,
2137 "OpenGl_TriangleSet does not contain transform", Standard_False);
2139 aNodeTransforms[anElemIndex] = aTransform->Inversed();
2142 aResult &= mySceneTransformTexture->Init (theGlContext, 4,
2143 myRaytraceGeometry.Size() * 4, reinterpret_cast<const GLfloat*> (aNodeTransforms));
2145 delete [] aNodeTransforms;
2147 /////////////////////////////////////////////////////////////////////////////
2148 // Write geometry and bottom-level BVH buffers
2150 Standard_Size aTotalVerticesNb = 0;
2151 Standard_Size aTotalElementsNb = 0;
2152 Standard_Size aTotalBVHNodesNb = 0;
2154 for (Standard_Integer anElemIndex = 0; anElemIndex < myRaytraceGeometry.Size(); ++anElemIndex)
2156 OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
2157 myRaytraceGeometry.Objects().ChangeValue (anElemIndex).operator->());
2159 Standard_ASSERT_RETURN (aTriangleSet != NULL,
2160 "Error: Failed to get triangulation of OpenGL element", Standard_False);
2162 aTotalVerticesNb += aTriangleSet->Vertices.size();
2163 aTotalElementsNb += aTriangleSet->Elements.size();
2165 Standard_ASSERT_RETURN (!aTriangleSet->QuadBVH().IsNull(),
2166 "Error: Failed to get bottom-level BVH of OpenGL element", Standard_False);
2168 aTotalBVHNodesNb += aTriangleSet->QuadBVH()->NodeInfoBuffer().size();
2171 aTotalBVHNodesNb += myRaytraceGeometry.QuadBVH()->NodeInfoBuffer().size();
2173 if (aTotalBVHNodesNb != 0)
2175 aResult &= mySceneNodeInfoTexture->Init (
2176 theGlContext, 4, GLsizei (aTotalBVHNodesNb), static_cast<const GLuint*> (NULL));
2177 aResult &= mySceneMinPointTexture->Init (
2178 theGlContext, 3, GLsizei (aTotalBVHNodesNb), static_cast<const GLfloat*> (NULL));
2179 aResult &= mySceneMaxPointTexture->Init (
2180 theGlContext, 3, GLsizei (aTotalBVHNodesNb), static_cast<const GLfloat*> (NULL));
2185 #ifdef RAY_TRACE_PRINT_INFO
2186 std::cout << "Error: Failed to upload buffers for bottom-level scene BVH" << std::endl;
2188 return Standard_False;
2191 if (aTotalElementsNb != 0)
2193 aResult &= myGeometryTriangTexture->Init (
2194 theGlContext, 4, GLsizei (aTotalElementsNb), static_cast<const GLuint*> (NULL));
2197 if (aTotalVerticesNb != 0)
2199 aResult &= myGeometryVertexTexture->Init (
2200 theGlContext, 3, GLsizei (aTotalVerticesNb), static_cast<const GLfloat*> (NULL));
2201 aResult &= myGeometryNormalTexture->Init (
2202 theGlContext, 3, GLsizei (aTotalVerticesNb), static_cast<const GLfloat*> (NULL));
2203 aResult &= myGeometryTexCrdTexture->Init (
2204 theGlContext, 2, GLsizei (aTotalVerticesNb), static_cast<const GLfloat*> (NULL));
2209 #ifdef RAY_TRACE_PRINT_INFO
2210 std::cout << "Error: Failed to upload buffers for scene geometry" << std::endl;
2212 return Standard_False;
2215 const QuadBvhHandle& aBVH = myRaytraceGeometry.QuadBVH();
2217 if (aBVH->Length() > 0)
2219 aResult &= mySceneNodeInfoTexture->SubData (theGlContext, 0, aBVH->Length(),
2220 reinterpret_cast<const GLuint*> (&aBVH->NodeInfoBuffer().front()));
2221 aResult &= mySceneMinPointTexture->SubData (theGlContext, 0, aBVH->Length(),
2222 reinterpret_cast<const GLfloat*> (&aBVH->MinPointBuffer().front()));
2223 aResult &= mySceneMaxPointTexture->SubData (theGlContext, 0, aBVH->Length(),
2224 reinterpret_cast<const GLfloat*> (&aBVH->MaxPointBuffer().front()));
2227 for (Standard_Integer aNodeIdx = 0; aNodeIdx < aBVH->Length(); ++aNodeIdx)
2229 if (!aBVH->IsOuter (aNodeIdx))
2232 OpenGl_TriangleSet* aTriangleSet = myRaytraceGeometry.TriangleSet (aNodeIdx);
2234 Standard_ASSERT_RETURN (aTriangleSet != NULL,
2235 "Error: Failed to get triangulation of OpenGL element", Standard_False);
2237 Standard_Integer aBVHOffset = myRaytraceGeometry.AccelerationOffset (aNodeIdx);
2239 Standard_ASSERT_RETURN (aBVHOffset != OpenGl_RaytraceGeometry::INVALID_OFFSET,
2240 "Error: Failed to get offset for bottom-level BVH", Standard_False);
2242 const Standard_Integer aBvhBuffersSize = aTriangleSet->QuadBVH()->Length();
2244 if (aBvhBuffersSize != 0)
2246 aResult &= mySceneNodeInfoTexture->SubData (theGlContext, aBVHOffset, aBvhBuffersSize,
2247 reinterpret_cast<const GLuint*> (&aTriangleSet->QuadBVH()->NodeInfoBuffer().front()));
2248 aResult &= mySceneMinPointTexture->SubData (theGlContext, aBVHOffset, aBvhBuffersSize,
2249 reinterpret_cast<const GLfloat*> (&aTriangleSet->QuadBVH()->MinPointBuffer().front()));
2250 aResult &= mySceneMaxPointTexture->SubData (theGlContext, aBVHOffset, aBvhBuffersSize,
2251 reinterpret_cast<const GLfloat*> (&aTriangleSet->QuadBVH()->MaxPointBuffer().front()));
2255 #ifdef RAY_TRACE_PRINT_INFO
2256 std::cout << "Error: Failed to upload buffers for bottom-level scene BVHs" << std::endl;
2258 return Standard_False;
2262 const Standard_Integer aVerticesOffset = myRaytraceGeometry.VerticesOffset (aNodeIdx);
2264 Standard_ASSERT_RETURN (aVerticesOffset != OpenGl_RaytraceGeometry::INVALID_OFFSET,
2265 "Error: Failed to get offset for triangulation vertices of OpenGL element", Standard_False);
2267 if (!aTriangleSet->Vertices.empty())
2269 aResult &= myGeometryNormalTexture->SubData (theGlContext, aVerticesOffset,
2270 GLsizei (aTriangleSet->Normals.size()), reinterpret_cast<const GLfloat*> (&aTriangleSet->Normals.front()));
2271 aResult &= myGeometryTexCrdTexture->SubData (theGlContext, aVerticesOffset,
2272 GLsizei (aTriangleSet->TexCrds.size()), reinterpret_cast<const GLfloat*> (&aTriangleSet->TexCrds.front()));
2273 aResult &= myGeometryVertexTexture->SubData (theGlContext, aVerticesOffset,
2274 GLsizei (aTriangleSet->Vertices.size()), reinterpret_cast<const GLfloat*> (&aTriangleSet->Vertices.front()));
2277 const Standard_Integer anElementsOffset = myRaytraceGeometry.ElementsOffset (aNodeIdx);
2279 Standard_ASSERT_RETURN (anElementsOffset != OpenGl_RaytraceGeometry::INVALID_OFFSET,
2280 "Error: Failed to get offset for triangulation elements of OpenGL element", Standard_False);
2282 if (!aTriangleSet->Elements.empty())
2284 aResult &= myGeometryTriangTexture->SubData (theGlContext, anElementsOffset, GLsizei (aTriangleSet->Elements.size()),
2285 reinterpret_cast<const GLuint*> (&aTriangleSet->Elements.front()));
2290 #ifdef RAY_TRACE_PRINT_INFO
2291 std::cout << "Error: Failed to upload triangulation buffers for OpenGL element" << std::endl;
2293 return Standard_False;
2297 /////////////////////////////////////////////////////////////////////////////
2298 // Write material buffer
2300 if (myRaytraceGeometry.Materials.size() != 0)
2302 aResult &= myRaytraceMaterialTexture->Init (theGlContext, 4,
2303 GLsizei (myRaytraceGeometry.Materials.size() * 19), myRaytraceGeometry.Materials.front().Packed());
2307 #ifdef RAY_TRACE_PRINT_INFO
2308 std::cout << "Error: Failed to upload material buffer" << std::endl;
2310 return Standard_False;
2314 myIsRaytraceDataValid = myRaytraceGeometry.Objects().Size() != 0;
2316 #ifdef RAY_TRACE_PRINT_INFO
2318 Standard_ShortReal aMemTrgUsed = 0.f;
2319 Standard_ShortReal aMemBvhUsed = 0.f;
2321 for (Standard_Integer anElemIdx = 0; anElemIdx < myRaytraceGeometry.Size(); ++anElemIdx)
2323 OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (myRaytraceGeometry.Objects()(anElemIdx).get());
2325 aMemTrgUsed += static_cast<Standard_ShortReal> (
2326 aTriangleSet->Vertices.size() * sizeof (BVH_Vec3f));
2327 aMemTrgUsed += static_cast<Standard_ShortReal> (
2328 aTriangleSet->Normals.size() * sizeof (BVH_Vec3f));
2329 aMemTrgUsed += static_cast<Standard_ShortReal> (
2330 aTriangleSet->TexCrds.size() * sizeof (BVH_Vec2f));
2331 aMemTrgUsed += static_cast<Standard_ShortReal> (
2332 aTriangleSet->Elements.size() * sizeof (BVH_Vec4i));
2334 aMemBvhUsed += static_cast<Standard_ShortReal> (
2335 aTriangleSet->QuadBVH()->NodeInfoBuffer().size() * sizeof (BVH_Vec4i));
2336 aMemBvhUsed += static_cast<Standard_ShortReal> (
2337 aTriangleSet->QuadBVH()->MinPointBuffer().size() * sizeof (BVH_Vec3f));
2338 aMemBvhUsed += static_cast<Standard_ShortReal> (
2339 aTriangleSet->QuadBVH()->MaxPointBuffer().size() * sizeof (BVH_Vec3f));
2342 aMemBvhUsed += static_cast<Standard_ShortReal> (
2343 myRaytraceGeometry.QuadBVH()->NodeInfoBuffer().size() * sizeof (BVH_Vec4i));
2344 aMemBvhUsed += static_cast<Standard_ShortReal> (
2345 myRaytraceGeometry.QuadBVH()->MinPointBuffer().size() * sizeof (BVH_Vec3f));
2346 aMemBvhUsed += static_cast<Standard_ShortReal> (
2347 myRaytraceGeometry.QuadBVH()->MaxPointBuffer().size() * sizeof (BVH_Vec3f));
2349 std::cout << "GPU Memory Used (Mb):\n"
2350 << "\tFor mesh: " << aMemTrgUsed / 1048576 << "\n"
2351 << "\tFor BVHs: " << aMemBvhUsed / 1048576 << "\n";
2358 // =======================================================================
2359 // function : updateRaytraceLightSources
2360 // purpose : Updates 3D scene light sources for ray-tracing
2361 // =======================================================================
2362 Standard_Boolean OpenGl_View::updateRaytraceLightSources (const OpenGl_Mat4& theInvModelView, const Handle(OpenGl_Context)& theGlContext)
2364 std::vector<Handle(Graphic3d_CLight)> aLightSources;
2365 myRaytraceGeometry.Ambient = BVH_Vec4f (0.f, 0.f, 0.f, 0.f);
2366 if (myShadingModel != Graphic3d_TOSM_UNLIT
2367 && !myLights.IsNull())
2369 const Graphic3d_Vec4& anAmbient = myLights->AmbientColor();
2370 myRaytraceGeometry.Ambient = BVH_Vec4f (anAmbient.r(), anAmbient.g(), anAmbient.b(), 0.0f);
2372 // move positional light sources at the front of the list
2373 aLightSources.reserve (myLights->Extent());
2374 for (Graphic3d_LightSet::Iterator aLightIter (myLights, Graphic3d_LightSet::IterationFilter_ExcludeDisabledAndAmbient);
2375 aLightIter.More(); aLightIter.Next())
2377 const Graphic3d_CLight& aLight = *aLightIter.Value();
2378 if (aLight.Type() != Graphic3d_TOLS_DIRECTIONAL)
2380 aLightSources.push_back (aLightIter.Value());
2384 for (Graphic3d_LightSet::Iterator aLightIter (myLights, Graphic3d_LightSet::IterationFilter_ExcludeDisabledAndAmbient);
2385 aLightIter.More(); aLightIter.Next())
2387 if (aLightIter.Value()->Type() == Graphic3d_TOLS_DIRECTIONAL)
2389 aLightSources.push_back (aLightIter.Value());
2394 // get number of 'real' (not ambient) light sources
2395 const size_t aNbLights = aLightSources.size();
2396 Standard_Boolean wasUpdated = myRaytraceGeometry.Sources.size () != aNbLights;
2399 myRaytraceGeometry.Sources.resize (aNbLights);
2402 for (size_t aLightIdx = 0, aRealIdx = 0; aLightIdx < aLightSources.size(); ++aLightIdx)
2404 const Graphic3d_CLight& aLight = *aLightSources[aLightIdx];
2405 const Graphic3d_Vec4& aLightColor = aLight.PackedColor();
2406 BVH_Vec4f aEmission (aLightColor.r() * aLight.Intensity(),
2407 aLightColor.g() * aLight.Intensity(),
2408 aLightColor.b() * aLight.Intensity(),
2411 BVH_Vec4f aPosition (-aLight.PackedDirection().x(),
2412 -aLight.PackedDirection().y(),
2413 -aLight.PackedDirection().z(),
2416 if (aLight.Type() != Graphic3d_TOLS_DIRECTIONAL)
2418 aPosition = BVH_Vec4f (static_cast<float>(aLight.Position().X()),
2419 static_cast<float>(aLight.Position().Y()),
2420 static_cast<float>(aLight.Position().Z()),
2423 // store smoothing radius in W-component
2424 aEmission.w() = Max (aLight.Smoothness(), 0.f);
2428 // store cosine of smoothing angle in W-component
2429 aEmission.w() = cosf (Min (Max (aLight.Smoothness(), 0.f), static_cast<Standard_ShortReal> (M_PI / 2.0)));
2432 if (aLight.IsHeadlight())
2434 aPosition = theInvModelView * aPosition;
2437 for (int aK = 0; aK < 4; ++aK)
2439 wasUpdated |= (aEmission[aK] != myRaytraceGeometry.Sources[aRealIdx].Emission[aK])
2440 || (aPosition[aK] != myRaytraceGeometry.Sources[aRealIdx].Position[aK]);
2445 myRaytraceGeometry.Sources[aRealIdx] = OpenGl_RaytraceLight (aEmission, aPosition);
2451 if (myRaytraceLightSrcTexture.IsNull()) // create light source buffer
2453 myRaytraceLightSrcTexture = new OpenGl_TextureBufferArb;
2456 if (myRaytraceGeometry.Sources.size() != 0 && wasUpdated)
2458 const GLfloat* aDataPtr = myRaytraceGeometry.Sources.front().Packed();
2459 if (!myRaytraceLightSrcTexture->Init (theGlContext, 4, GLsizei (myRaytraceGeometry.Sources.size() * 2), aDataPtr))
2461 #ifdef RAY_TRACE_PRINT_INFO
2462 std::cout << "Error: Failed to upload light source buffer" << std::endl;
2464 return Standard_False;
2467 myAccumFrames = 0; // accumulation should be restarted
2470 return Standard_True;
2473 // =======================================================================
2474 // function : setUniformState
2475 // purpose : Sets uniform state for the given ray-tracing shader program
2476 // =======================================================================
2477 Standard_Boolean OpenGl_View::setUniformState (const Standard_Integer theProgramId,
2478 const Standard_Integer theWinSizeX,
2479 const Standard_Integer theWinSizeY,
2480 Graphic3d_Camera::Projection theProjection,
2481 const Handle(OpenGl_Context)& theGlContext)
2483 // Get projection state
2484 OpenGl_MatrixState<Standard_ShortReal>& aCntxProjectionState = theGlContext->ProjectionState;
2486 OpenGl_Mat4 aViewPrjMat;
2487 OpenGl_Mat4 anUnviewMat;
2488 OpenGl_Vec3 aOrigins[4];
2489 OpenGl_Vec3 aDirects[4];
2491 if (myCamera->IsOrthographic()
2492 || !myRenderParams.IsGlobalIlluminationEnabled)
2494 updateCamera (myCamera->OrientationMatrixF(),
2495 aCntxProjectionState.Current(),
2503 updatePerspCameraPT (myCamera->OrientationMatrixF(),
2504 aCntxProjectionState.Current(),
2512 Handle(OpenGl_ShaderProgram)& theProgram = theProgramId == 0
2514 : myPostFSAAProgram;
2516 if (theProgram.IsNull())
2518 return Standard_False;
2521 theProgram->SetUniform(theGlContext, "uEyeOrig", myEyeOrig);
2522 theProgram->SetUniform(theGlContext, "uEyeView", myEyeView);
2523 theProgram->SetUniform(theGlContext, "uEyeVert", myEyeVert);
2524 theProgram->SetUniform(theGlContext, "uEyeSide", myEyeSide);
2525 theProgram->SetUniform(theGlContext, "uEyeSize", myEyeSize);
2527 theProgram->SetUniform(theGlContext, "uApertureRadius", myRenderParams.CameraApertureRadius);
2528 theProgram->SetUniform(theGlContext, "uFocalPlaneDist", myRenderParams.CameraFocalPlaneDist);
2531 theProgram->SetUniform (theGlContext,
2532 myUniformLocations[theProgramId][OpenGl_RT_uOriginLB], aOrigins[0]);
2533 theProgram->SetUniform (theGlContext,
2534 myUniformLocations[theProgramId][OpenGl_RT_uOriginRB], aOrigins[1]);
2535 theProgram->SetUniform (theGlContext,
2536 myUniformLocations[theProgramId][OpenGl_RT_uOriginLT], aOrigins[2]);
2537 theProgram->SetUniform (theGlContext,
2538 myUniformLocations[theProgramId][OpenGl_RT_uOriginRT], aOrigins[3]);
2539 theProgram->SetUniform (theGlContext,
2540 myUniformLocations[theProgramId][OpenGl_RT_uDirectLB], aDirects[0]);
2541 theProgram->SetUniform (theGlContext,
2542 myUniformLocations[theProgramId][OpenGl_RT_uDirectRB], aDirects[1]);
2543 theProgram->SetUniform (theGlContext,
2544 myUniformLocations[theProgramId][OpenGl_RT_uDirectLT], aDirects[2]);
2545 theProgram->SetUniform (theGlContext,
2546 myUniformLocations[theProgramId][OpenGl_RT_uDirectRT], aDirects[3]);
2547 theProgram->SetUniform (theGlContext,
2548 myUniformLocations[theProgramId][OpenGl_RT_uViewPrMat], aViewPrjMat);
2549 theProgram->SetUniform (theGlContext,
2550 myUniformLocations[theProgramId][OpenGl_RT_uUnviewMat], anUnviewMat);
2552 // Set screen dimensions
2553 myRaytraceProgram->SetUniform (theGlContext,
2554 myUniformLocations[theProgramId][OpenGl_RT_uWinSizeX], theWinSizeX);
2555 myRaytraceProgram->SetUniform (theGlContext,
2556 myUniformLocations[theProgramId][OpenGl_RT_uWinSizeY], theWinSizeY);
2558 // Set 3D scene parameters
2559 theProgram->SetUniform (theGlContext,
2560 myUniformLocations[theProgramId][OpenGl_RT_uSceneRad], myRaytraceSceneRadius);
2561 theProgram->SetUniform (theGlContext,
2562 myUniformLocations[theProgramId][OpenGl_RT_uSceneEps], myRaytraceSceneEpsilon);
2564 // Set light source parameters
2565 const Standard_Integer aLightSourceBufferSize =
2566 static_cast<Standard_Integer> (myRaytraceGeometry.Sources.size());
2568 theProgram->SetUniform (theGlContext,
2569 myUniformLocations[theProgramId][OpenGl_RT_uLightCount], aLightSourceBufferSize);
2571 // Set array of 64-bit texture handles
2572 if (theGlContext->arbTexBindless != NULL && myRaytraceGeometry.HasTextures())
2574 const std::vector<GLuint64>& aTextures = myRaytraceGeometry.TextureHandles();
2576 theProgram->SetUniform (theGlContext, myUniformLocations[theProgramId][OpenGl_RT_uTexSamplersArray],
2577 static_cast<GLsizei> (aTextures.size()), reinterpret_cast<const OpenGl_Vec2u*> (&aTextures.front()));
2580 // Set background colors (only vertical gradient background supported)
2581 OpenGl_Vec4 aBackColorTop = myBgColor, aBackColorBot = myBgColor;
2582 if (myBackgrounds[Graphic3d_TOB_GRADIENT] != NULL
2583 && myBackgrounds[Graphic3d_TOB_GRADIENT]->IsDefined())
2585 aBackColorTop = myBackgrounds[Graphic3d_TOB_GRADIENT]->GradientColor (0);
2586 aBackColorBot = myBackgrounds[Graphic3d_TOB_GRADIENT]->GradientColor (1);
2588 aBackColorTop = theGlContext->Vec4FromQuantityColor (aBackColorTop);
2589 aBackColorBot = theGlContext->Vec4FromQuantityColor (aBackColorBot);
2590 theProgram->SetUniform (theGlContext, myUniformLocations[theProgramId][OpenGl_RT_uBackColorTop], aBackColorTop);
2591 theProgram->SetUniform (theGlContext, myUniformLocations[theProgramId][OpenGl_RT_uBackColorBot], aBackColorBot);
2593 // Set environment map parameters
2594 const Standard_Boolean toDisableEnvironmentMap = myTextureEnv.IsNull()
2595 || myTextureEnv->IsEmpty()
2596 || !myTextureEnv->First()->IsValid();
2598 theProgram->SetUniform (theGlContext,
2599 myUniformLocations[theProgramId][OpenGl_RT_uSphereMapEnabled], toDisableEnvironmentMap ? 0 : 1);
2601 theProgram->SetUniform (theGlContext,
2602 myUniformLocations[theProgramId][OpenGl_RT_uSphereMapForBack], myRenderParams.UseEnvironmentMapBackground ? 1 : 0);
2604 if (myRenderParams.IsGlobalIlluminationEnabled) // GI parameters
2606 theProgram->SetUniform (theGlContext,
2607 myUniformLocations[theProgramId][OpenGl_RT_uMaxRadiance], myRenderParams.RadianceClampingValue);
2609 theProgram->SetUniform (theGlContext,
2610 myUniformLocations[theProgramId][OpenGl_RT_uBlockedRngEnabled], myRenderParams.CoherentPathTracingMode ? 1 : 0);
2612 // Check whether we should restart accumulation for run-time parameters
2613 if (myRenderParams.RadianceClampingValue != myRaytraceParameters.RadianceClampingValue
2614 || myRenderParams.UseEnvironmentMapBackground != myRaytraceParameters.UseEnvMapForBackground)
2616 myAccumFrames = 0; // accumulation should be restarted
2618 myRaytraceParameters.RadianceClampingValue = myRenderParams.RadianceClampingValue;
2619 myRaytraceParameters.UseEnvMapForBackground = myRenderParams.UseEnvironmentMapBackground;
2622 else // RT parameters
2624 // Set ambient light source
2625 theProgram->SetUniform (theGlContext,
2626 myUniformLocations[theProgramId][OpenGl_RT_uLightAmbnt], myRaytraceGeometry.Ambient);
2628 // Enable/disable run-time ray-tracing effects
2629 theProgram->SetUniform (theGlContext,
2630 myUniformLocations[theProgramId][OpenGl_RT_uShadowsEnabled], myRenderParams.IsShadowEnabled ? 1 : 0);
2631 theProgram->SetUniform (theGlContext,
2632 myUniformLocations[theProgramId][OpenGl_RT_uReflectEnabled], myRenderParams.IsReflectionEnabled ? 1 : 0);
2635 return Standard_True;
2638 // =======================================================================
2639 // function : bindRaytraceTextures
2640 // purpose : Binds ray-trace textures to corresponding texture units
2641 // =======================================================================
2642 void OpenGl_View::bindRaytraceTextures (const Handle(OpenGl_Context)& theGlContext,
2645 if (myRaytraceParameters.AdaptiveScreenSampling
2646 && myRaytraceParameters.GlobalIllumination)
2648 #if !defined(GL_ES_VERSION_2_0)
2649 theGlContext->core42->glBindImageTexture (OpenGl_RT_OutputImage,
2650 myRaytraceOutputTexture[theStereoView]->TextureId(), 0, GL_TRUE, 0, GL_READ_WRITE, GL_R32F);
2651 theGlContext->core42->glBindImageTexture (OpenGl_RT_VisualErrorImage,
2652 myRaytraceVisualErrorTexture[theStereoView]->TextureId(), 0, GL_TRUE, 0, GL_READ_WRITE, GL_R32I);
2653 if (myRaytraceParameters.AdaptiveScreenSamplingAtomic)
2655 theGlContext->core42->glBindImageTexture (OpenGl_RT_TileOffsetsImage,
2656 myRaytraceTileOffsetsTexture[theStereoView]->TextureId(), 0, GL_TRUE, 0, GL_READ_ONLY, GL_RG32I);
2660 theGlContext->core42->glBindImageTexture (OpenGl_RT_TileSamplesImage,
2661 myRaytraceTileSamplesTexture[theStereoView]->TextureId(), 0, GL_TRUE, 0, GL_READ_WRITE, GL_R32I);
2664 (void )theStereoView;
2668 if (!myTextureEnv.IsNull()
2669 && !myTextureEnv->IsEmpty()
2670 && myTextureEnv->First()->IsValid())
2672 myTextureEnv->First()->Bind (theGlContext, OpenGl_RT_EnvironmentMapTexture);
2675 mySceneMinPointTexture ->BindTexture (theGlContext, OpenGl_RT_SceneMinPointTexture);
2676 mySceneMaxPointTexture ->BindTexture (theGlContext, OpenGl_RT_SceneMaxPointTexture);
2677 mySceneNodeInfoTexture ->BindTexture (theGlContext, OpenGl_RT_SceneNodeInfoTexture);
2678 myGeometryVertexTexture ->BindTexture (theGlContext, OpenGl_RT_GeometryVertexTexture);
2679 myGeometryNormalTexture ->BindTexture (theGlContext, OpenGl_RT_GeometryNormalTexture);
2680 myGeometryTexCrdTexture ->BindTexture (theGlContext, OpenGl_RT_GeometryTexCrdTexture);
2681 myGeometryTriangTexture ->BindTexture (theGlContext, OpenGl_RT_GeometryTriangTexture);
2682 mySceneTransformTexture ->BindTexture (theGlContext, OpenGl_RT_SceneTransformTexture);
2683 myRaytraceMaterialTexture->BindTexture (theGlContext, OpenGl_RT_RaytraceMaterialTexture);
2684 myRaytraceLightSrcTexture->BindTexture (theGlContext, OpenGl_RT_RaytraceLightSrcTexture);
2687 // =======================================================================
2688 // function : unbindRaytraceTextures
2689 // purpose : Unbinds ray-trace textures from corresponding texture units
2690 // =======================================================================
2691 void OpenGl_View::unbindRaytraceTextures (const Handle(OpenGl_Context)& theGlContext)
2693 mySceneMinPointTexture ->UnbindTexture (theGlContext, OpenGl_RT_SceneMinPointTexture);
2694 mySceneMaxPointTexture ->UnbindTexture (theGlContext, OpenGl_RT_SceneMaxPointTexture);
2695 mySceneNodeInfoTexture ->UnbindTexture (theGlContext, OpenGl_RT_SceneNodeInfoTexture);
2696 myGeometryVertexTexture ->UnbindTexture (theGlContext, OpenGl_RT_GeometryVertexTexture);
2697 myGeometryNormalTexture ->UnbindTexture (theGlContext, OpenGl_RT_GeometryNormalTexture);
2698 myGeometryTexCrdTexture ->UnbindTexture (theGlContext, OpenGl_RT_GeometryTexCrdTexture);
2699 myGeometryTriangTexture ->UnbindTexture (theGlContext, OpenGl_RT_GeometryTriangTexture);
2700 mySceneTransformTexture ->UnbindTexture (theGlContext, OpenGl_RT_SceneTransformTexture);
2701 myRaytraceMaterialTexture->UnbindTexture (theGlContext, OpenGl_RT_RaytraceMaterialTexture);
2702 myRaytraceLightSrcTexture->UnbindTexture (theGlContext, OpenGl_RT_RaytraceLightSrcTexture);
2704 theGlContext->core15fwd->glActiveTexture (GL_TEXTURE0);
2707 // =======================================================================
2708 // function : runRaytraceShaders
2709 // purpose : Runs ray-tracing shader programs
2710 // =======================================================================
2711 Standard_Boolean OpenGl_View::runRaytraceShaders (const Standard_Integer theSizeX,
2712 const Standard_Integer theSizeY,
2713 Graphic3d_Camera::Projection theProjection,
2714 OpenGl_FrameBuffer* theReadDrawFbo,
2715 const Handle(OpenGl_Context)& theGlContext)
2717 Standard_Boolean aResult = theGlContext->BindProgram (myRaytraceProgram);
2719 aResult &= setUniformState (0,
2725 if (myRaytraceParameters.GlobalIllumination) // path tracing
2727 aResult &= runPathtrace (theSizeX, theSizeY, theProjection, theGlContext);
2728 aResult &= runPathtraceOut (theProjection, theReadDrawFbo, theGlContext);
2730 else // Whitted-style ray-tracing
2732 aResult &= runRaytrace (theSizeX, theSizeY, theProjection, theReadDrawFbo, theGlContext);
2738 // =======================================================================
2739 // function : runRaytrace
2740 // purpose : Runs Whitted-style ray-tracing
2741 // =======================================================================
2742 Standard_Boolean OpenGl_View::runRaytrace (const Standard_Integer theSizeX,
2743 const Standard_Integer theSizeY,
2744 Graphic3d_Camera::Projection theProjection,
2745 OpenGl_FrameBuffer* theReadDrawFbo,
2746 const Handle(OpenGl_Context)& theGlContext)
2748 Standard_Boolean aResult = Standard_True;
2750 // Choose proper set of frame buffers for stereo rendering
2751 const Standard_Integer aFBOIdx = (theProjection == Graphic3d_Camera::Projection_MonoRightEye) ? 1 : 0;
2752 bindRaytraceTextures (theGlContext, aFBOIdx);
2754 if (myRenderParams.IsAntialiasingEnabled) // if second FSAA pass is used
2756 myRaytraceFBO1[aFBOIdx]->BindBuffer (theGlContext);
2758 glClear (GL_DEPTH_BUFFER_BIT); // render the image with depth
2761 theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
2763 if (myRenderParams.IsAntialiasingEnabled)
2765 glDisable (GL_DEPTH_TEST); // improve jagged edges without depth buffer
2767 // bind ray-tracing output image as input
2768 myRaytraceFBO1[aFBOIdx]->ColorTexture()->Bind (theGlContext, OpenGl_RT_FsaaInputTexture);
2770 aResult &= theGlContext->BindProgram (myPostFSAAProgram);
2772 aResult &= setUniformState (1 /* FSAA ID */,
2778 // Perform multi-pass adaptive FSAA using ping-pong technique.
2779 // We use 'FLIPTRI' sampling pattern changing for every pixel
2780 // (3 additional samples per pixel, the 1st sample is already
2781 // available from initial ray-traced image).
2782 for (Standard_Integer anIt = 1; anIt < 4; ++anIt)
2784 GLfloat aOffsetX = 1.f / theSizeX;
2785 GLfloat aOffsetY = 1.f / theSizeY;
2803 aResult &= myPostFSAAProgram->SetUniform (theGlContext,
2804 myUniformLocations[1][OpenGl_RT_uSamples], anIt + 1);
2805 aResult &= myPostFSAAProgram->SetUniform (theGlContext,
2806 myUniformLocations[1][OpenGl_RT_uOffsetX], aOffsetX);
2807 aResult &= myPostFSAAProgram->SetUniform (theGlContext,
2808 myUniformLocations[1][OpenGl_RT_uOffsetY], aOffsetY);
2810 Handle(OpenGl_FrameBuffer)& aFramebuffer = anIt % 2
2811 ? myRaytraceFBO2[aFBOIdx]
2812 : myRaytraceFBO1[aFBOIdx];
2814 aFramebuffer->BindBuffer (theGlContext);
2816 // perform adaptive FSAA pass
2817 theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
2819 aFramebuffer->ColorTexture()->Bind (theGlContext, OpenGl_RT_FsaaInputTexture);
2822 const Handle(OpenGl_FrameBuffer)& aRenderImageFramebuffer = myRaytraceFBO2[aFBOIdx];
2823 const Handle(OpenGl_FrameBuffer)& aDepthSourceFramebuffer = myRaytraceFBO1[aFBOIdx];
2825 glEnable (GL_DEPTH_TEST);
2827 // Display filtered image
2828 theGlContext->BindProgram (myOutImageProgram);
2830 if (theReadDrawFbo != NULL)
2832 theReadDrawFbo->BindBuffer (theGlContext);
2836 aRenderImageFramebuffer->UnbindBuffer (theGlContext);
2839 aRenderImageFramebuffer->ColorTexture() ->Bind (theGlContext, OpenGl_RT_PrevAccumTexture);
2840 aDepthSourceFramebuffer->DepthStencilTexture()->Bind (theGlContext, OpenGl_RT_RaytraceDepthTexture);
2842 // copy the output image with depth values
2843 theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
2845 aDepthSourceFramebuffer->DepthStencilTexture()->Unbind (theGlContext, OpenGl_RT_RaytraceDepthTexture);
2846 aRenderImageFramebuffer->ColorTexture() ->Unbind (theGlContext, OpenGl_RT_PrevAccumTexture);
2849 unbindRaytraceTextures (theGlContext);
2851 theGlContext->BindProgram (NULL);
2856 // =======================================================================
2857 // function : runPathtrace
2858 // purpose : Runs path tracing shader
2859 // =======================================================================
2860 Standard_Boolean OpenGl_View::runPathtrace (const Standard_Integer theSizeX,
2861 const Standard_Integer theSizeY,
2862 const Graphic3d_Camera::Projection theProjection,
2863 const Handle(OpenGl_Context)& theGlContext)
2865 if (myToUpdateEnvironmentMap) // check whether the map was changed
2867 myAccumFrames = myToUpdateEnvironmentMap = 0;
2870 if (myRenderParams.CameraApertureRadius != myPrevCameraApertureRadius
2871 || myRenderParams.CameraFocalPlaneDist != myPrevCameraFocalPlaneDist)
2873 myPrevCameraApertureRadius = myRenderParams.CameraApertureRadius;
2874 myPrevCameraFocalPlaneDist = myRenderParams.CameraFocalPlaneDist;
2878 // Choose proper set of frame buffers for stereo rendering
2879 const Standard_Integer aFBOIdx = (theProjection == Graphic3d_Camera::Projection_MonoRightEye) ? 1 : 0;
2881 if (myRaytraceParameters.AdaptiveScreenSampling)
2883 if (myAccumFrames == 0)
2885 myTileSampler.Reset(); // reset tile sampler to its initial state
2887 // Adaptive sampling is starting at the second frame
2888 if (myRaytraceParameters.AdaptiveScreenSamplingAtomic)
2890 myTileSampler.UploadOffsets (theGlContext, myRaytraceTileOffsetsTexture[aFBOIdx], false);
2894 myTileSampler.UploadSamples (theGlContext, myRaytraceTileSamplesTexture[aFBOIdx], false);
2897 #if !defined(GL_ES_VERSION_2_0)
2898 theGlContext->core44->glClearTexImage (myRaytraceOutputTexture[aFBOIdx]->TextureId(), 0, GL_RED, GL_FLOAT, NULL);
2902 // Clear adaptive screen sampling images
2903 #if !defined(GL_ES_VERSION_2_0)
2904 theGlContext->core44->glClearTexImage (myRaytraceVisualErrorTexture[aFBOIdx]->TextureId(), 0, GL_RED_INTEGER, GL_INT, NULL);
2908 bindRaytraceTextures (theGlContext, aFBOIdx);
2910 const Handle(OpenGl_FrameBuffer)& anAccumImageFramebuffer = myAccumFrames % 2 ? myRaytraceFBO2[aFBOIdx] : myRaytraceFBO1[aFBOIdx];
2911 anAccumImageFramebuffer->ColorTexture()->Bind (theGlContext, OpenGl_RT_PrevAccumTexture);
2913 // Set frame accumulation weight
2914 myRaytraceProgram->SetUniform (theGlContext, myUniformLocations[0][OpenGl_RT_uAccumSamples], myAccumFrames);
2916 // Set image uniforms for render program
2917 if (myRaytraceParameters.AdaptiveScreenSampling)
2919 myRaytraceProgram->SetUniform (theGlContext, myUniformLocations[0][OpenGl_RT_uRenderImage], OpenGl_RT_OutputImage);
2920 myRaytraceProgram->SetUniform (theGlContext, myUniformLocations[0][OpenGl_RT_uTilesImage], OpenGl_RT_TileSamplesImage);
2921 myRaytraceProgram->SetUniform (theGlContext, myUniformLocations[0][OpenGl_RT_uOffsetImage], OpenGl_RT_TileOffsetsImage);
2922 myRaytraceProgram->SetUniform (theGlContext, myUniformLocations[0][OpenGl_RT_uTileSize], myTileSampler.TileSize());
2925 const Handle(OpenGl_FrameBuffer)& aRenderImageFramebuffer = myAccumFrames % 2 ? myRaytraceFBO1[aFBOIdx] : myRaytraceFBO2[aFBOIdx];
2926 aRenderImageFramebuffer->BindBuffer (theGlContext);
2927 if (myRaytraceParameters.AdaptiveScreenSampling
2928 && myRaytraceParameters.AdaptiveScreenSamplingAtomic)
2930 // extend viewport here, so that tiles at boundaries (cut tile size by target rendering viewport)
2931 // redirected to inner tiles (full tile size) are drawn entirely
2932 const Graphic3d_Vec2i anOffsetViewport = myTileSampler.OffsetTilesViewport (myAccumFrames > 1); // shrunk offsets texture will be uploaded since 3rd frame
2933 glViewport (0, 0, anOffsetViewport.x(), anOffsetViewport.y());
2936 // Generate for the given RNG seed
2937 glDisable (GL_DEPTH_TEST);
2939 // Adaptive Screen Sampling computes the same overall amount of samples per frame redraw as normal Path Tracing,
2940 // but distributes them unequally across pixels (grouped in tiles), so that some pixels do not receive new samples at all.
2942 // Offsets map (redirecting currently rendered tile to another tile) allows performing Adaptive Screen Sampling in single pass,
2943 // but current implementation relies on atomic float operations (AdaptiveScreenSamplingAtomic) for this.
2944 // So that when atomic floats are not supported by GPU, multi-pass rendering is used instead.
2946 // Single-pass rendering is more optimal due to smaller amount of draw calls,
2947 // memory synchronization barriers, discarding most of the fragments and bad parallelization in case of very small amount of tiles requiring more samples.
2948 // However, atomic operations on float values still produces different result (close, but not bit exact) making non-regression testing not robust.
2949 // It should be possible following single-pass rendering approach but using extra accumulation buffer and resolving pass as possible improvement.
2950 const int aNbPasses = myRaytraceParameters.AdaptiveScreenSampling
2951 && !myRaytraceParameters.AdaptiveScreenSamplingAtomic
2952 ? myTileSampler.MaxTileSamples()
2954 if (myAccumFrames == 0)
2956 myRNG.SetSeed(); // start RNG from beginning
2958 for (int aPassIter = 0; aPassIter < aNbPasses; ++aPassIter)
2960 myRaytraceProgram->SetUniform (theGlContext, myUniformLocations[0][OpenGl_RT_uFrameRndSeed], static_cast<Standard_Integer> (myRNG.NextInt() >> 2));
2961 theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
2962 if (myRaytraceParameters.AdaptiveScreenSampling)
2964 #if !defined(GL_ES_VERSION_2_0)
2965 theGlContext->core44->glMemoryBarrier (GL_SHADER_IMAGE_ACCESS_BARRIER_BIT);
2969 aRenderImageFramebuffer->UnbindBuffer (theGlContext);
2971 if (myRaytraceParameters.AdaptiveScreenSampling
2972 && myRaytraceParameters.AdaptiveScreenSamplingAtomic)
2974 glViewport (0, 0, theSizeX, theSizeY);
2979 // =======================================================================
2980 // function : runPathtraceOut
2982 // =======================================================================
2983 Standard_Boolean OpenGl_View::runPathtraceOut (const Graphic3d_Camera::Projection theProjection,
2984 OpenGl_FrameBuffer* theReadDrawFbo,
2985 const Handle(OpenGl_Context)& theGlContext)
2987 // Output accumulated path traced image
2988 theGlContext->BindProgram (myOutImageProgram);
2990 // Choose proper set of frame buffers for stereo rendering
2991 const Standard_Integer aFBOIdx = (theProjection == Graphic3d_Camera::Projection_MonoRightEye) ? 1 : 0;
2993 if (myRaytraceParameters.AdaptiveScreenSampling)
2995 // Set uniforms for display program
2996 myOutImageProgram->SetUniform (theGlContext, "uRenderImage", OpenGl_RT_OutputImage);
2997 myOutImageProgram->SetUniform (theGlContext, "uAccumFrames", myAccumFrames);
2998 myOutImageProgram->SetUniform (theGlContext, "uVarianceImage", OpenGl_RT_VisualErrorImage);
2999 myOutImageProgram->SetUniform (theGlContext, "uDebugAdaptive", myRenderParams.ShowSamplingTiles ? 1 : 0);
3000 myOutImageProgram->SetUniform (theGlContext, "uTileSize", myTileSampler.TileSize());
3001 myOutImageProgram->SetUniform (theGlContext, "uVarianceScaleFactor", myTileSampler.VarianceScaleFactor());
3004 if (myRaytraceParameters.GlobalIllumination)
3006 myOutImageProgram->SetUniform(theGlContext, "uExposure", myRenderParams.Exposure);
3007 switch (myRaytraceParameters.ToneMappingMethod)
3009 case Graphic3d_ToneMappingMethod_Disabled:
3011 case Graphic3d_ToneMappingMethod_Filmic:
3012 myOutImageProgram->SetUniform (theGlContext, "uWhitePoint", myRenderParams.WhitePoint);
3017 if (theReadDrawFbo != NULL)
3019 theReadDrawFbo->BindBuffer (theGlContext);
3022 const Handle(OpenGl_FrameBuffer)& aRenderImageFramebuffer = myAccumFrames % 2 ? myRaytraceFBO1[aFBOIdx] : myRaytraceFBO2[aFBOIdx];
3023 aRenderImageFramebuffer->ColorTexture()->Bind (theGlContext, OpenGl_RT_PrevAccumTexture);
3025 // Copy accumulated image with correct depth values
3026 glEnable (GL_DEPTH_TEST);
3027 theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
3029 aRenderImageFramebuffer->ColorTexture()->Unbind (theGlContext, OpenGl_RT_PrevAccumTexture);
3031 if (myRaytraceParameters.AdaptiveScreenSampling)
3033 // Download visual error map from the GPU and build adjusted tile offsets for optimal image sampling
3034 myTileSampler.GrabVarianceMap (theGlContext, myRaytraceVisualErrorTexture[aFBOIdx]);
3035 if (myRaytraceParameters.AdaptiveScreenSamplingAtomic)
3037 myTileSampler.UploadOffsets (theGlContext, myRaytraceTileOffsetsTexture[aFBOIdx], myAccumFrames != 0);
3041 myTileSampler.UploadSamples (theGlContext, myRaytraceTileSamplesTexture[aFBOIdx], myAccumFrames != 0);
3045 unbindRaytraceTextures (theGlContext);
3046 theGlContext->BindProgram (NULL);
3050 // =======================================================================
3051 // function : raytrace
3052 // purpose : Redraws the window using OpenGL/GLSL ray-tracing
3053 // =======================================================================
3054 Standard_Boolean OpenGl_View::raytrace (const Standard_Integer theSizeX,
3055 const Standard_Integer theSizeY,
3056 Graphic3d_Camera::Projection theProjection,
3057 OpenGl_FrameBuffer* theReadDrawFbo,
3058 const Handle(OpenGl_Context)& theGlContext)
3060 if (!initRaytraceResources (theSizeX, theSizeY, theGlContext))
3062 return Standard_False;
3065 if (!updateRaytraceBuffers (theSizeX, theSizeY, theGlContext))
3067 return Standard_False;
3070 OpenGl_Mat4 aLightSourceMatrix;
3072 // Get inversed model-view matrix for transforming lights
3073 myCamera->OrientationMatrixF().Inverted (aLightSourceMatrix);
3075 if (!updateRaytraceLightSources (aLightSourceMatrix, theGlContext))
3077 return Standard_False;
3080 // Generate image using Whitted-style ray-tracing or path tracing
3081 if (myIsRaytraceDataValid)
3083 myRaytraceScreenQuad.BindVertexAttrib (theGlContext, Graphic3d_TOA_POS);
3085 if (!myRaytraceGeometry.AcquireTextures (theGlContext))
3087 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR,
3088 0, GL_DEBUG_SEVERITY_MEDIUM, "Error: Failed to acquire OpenGL image textures");
3091 glDisable (GL_BLEND);
3093 const Standard_Boolean aResult = runRaytraceShaders (theSizeX,
3101 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR,
3102 0, GL_DEBUG_SEVERITY_MEDIUM, "Error: Failed to execute ray-tracing shaders");
3105 if (!myRaytraceGeometry.ReleaseTextures (theGlContext))
3107 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR,
3108 0, GL_DEBUG_SEVERITY_MEDIUM, "Error: Failed to release OpenGL image textures");
3111 myRaytraceScreenQuad.UnbindVertexAttrib (theGlContext, Graphic3d_TOA_POS);
3114 return Standard_True;