1 // Created on: 2015-02-20
2 // Created by: Denis BOGOLEPOV
3 // Copyright (c) 2015 OPEN CASCADE SAS
5 // This file is part of Open CASCADE Technology software library.
7 // This library is free software; you can redistribute it and/or modify it under
8 // the terms of the GNU Lesser General Public License version 2.1 as published
9 // by the Free Software Foundation, with special exception defined in the file
10 // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
11 // distribution for complete text of the license and disclaimer of any warranty.
13 // Alternatively, this file may be used under the terms of Open CASCADE
14 // commercial license or contractual agreement.
16 #include <OpenGl_View.hxx>
18 #include <Graphic3d_TextureParams.hxx>
19 #include <OpenGl_PrimitiveArray.hxx>
20 #include <OpenGl_VertexBuffer.hxx>
21 #include <OpenGl_GlCore44.hxx>
22 #include <OSD_Protection.hxx>
23 #include <OSD_File.hxx>
25 #include "../Shaders/Shaders_RaytraceBase_vs.pxx"
26 #include "../Shaders/Shaders_RaytraceBase_fs.pxx"
27 #include "../Shaders/Shaders_PathtraceBase_fs.pxx"
28 #include "../Shaders/Shaders_RaytraceRender_fs.pxx"
29 #include "../Shaders/Shaders_RaytraceSmooth_fs.pxx"
30 #include "../Shaders/Shaders_Display_fs.pxx"
32 using namespace OpenGl_Raytrace;
34 //! Use this macro to output ray-tracing debug info
35 // #define RAY_TRACE_PRINT_INFO
37 #ifdef RAY_TRACE_PRINT_INFO
38 #include <OSD_Timer.hxx>
43 static const OpenGl_Vec4 THE_WHITE_COLOR (1.0f, 1.0f, 1.0f, 1.0f);
44 static const OpenGl_Vec4 THE_BLACK_COLOR (0.0f, 0.0f, 0.0f, 1.0f);
46 //! Operator returning TRUE for positional light sources.
47 struct IsLightPositional
49 bool operator() (const OpenGl_Light& theLight)
51 return theLight.Type != Graphic3d_TOLS_DIRECTIONAL;
55 //! Operator returning TRUE for any non-ambient light sources.
58 bool operator() (const OpenGl_Light& theLight)
60 return theLight.Type != Graphic3d_TOLS_AMBIENT;
67 //! Defines OpenGL texture samplers.
68 static const Graphic3d_TextureUnit OpenGl_RT_EnvironmentMapTexture = Graphic3d_TextureUnit_0;
70 static const Graphic3d_TextureUnit OpenGl_RT_SceneNodeInfoTexture = Graphic3d_TextureUnit_1;
71 static const Graphic3d_TextureUnit OpenGl_RT_SceneMinPointTexture = Graphic3d_TextureUnit_2;
72 static const Graphic3d_TextureUnit OpenGl_RT_SceneMaxPointTexture = Graphic3d_TextureUnit_3;
73 static const Graphic3d_TextureUnit OpenGl_RT_SceneTransformTexture = Graphic3d_TextureUnit_4;
75 static const Graphic3d_TextureUnit OpenGl_RT_GeometryVertexTexture = Graphic3d_TextureUnit_5;
76 static const Graphic3d_TextureUnit OpenGl_RT_GeometryNormalTexture = Graphic3d_TextureUnit_6;
77 static const Graphic3d_TextureUnit OpenGl_RT_GeometryTexCrdTexture = Graphic3d_TextureUnit_7;
78 static const Graphic3d_TextureUnit OpenGl_RT_GeometryTriangTexture = Graphic3d_TextureUnit_8;
80 static const Graphic3d_TextureUnit OpenGl_RT_RaytraceMaterialTexture = Graphic3d_TextureUnit_9;
81 static const Graphic3d_TextureUnit OpenGl_RT_RaytraceLightSrcTexture = Graphic3d_TextureUnit_10;
83 static const Graphic3d_TextureUnit OpenGl_RT_FsaaInputTexture = Graphic3d_TextureUnit_11;
84 static const Graphic3d_TextureUnit OpenGl_RT_PrevAccumTexture = Graphic3d_TextureUnit_12;
86 static const Graphic3d_TextureUnit OpenGl_RT_RaytraceDepthTexture = Graphic3d_TextureUnit_13;
89 // =======================================================================
90 // function : updateRaytraceGeometry
91 // purpose : Updates 3D scene geometry for ray-tracing
92 // =======================================================================
93 Standard_Boolean OpenGl_View::updateRaytraceGeometry (const RaytraceUpdateMode theMode,
94 const Standard_Integer theViewId,
95 const Handle(OpenGl_Context)& theGlContext)
97 // In 'check' mode (OpenGl_GUM_CHECK) the scene geometry is analyzed for
98 // modifications. This is light-weight procedure performed on each frame
99 if (theMode == OpenGl_GUM_CHECK)
101 if (myRaytraceLayerListState != myZLayers.ModificationStateOfRaytracable())
103 return updateRaytraceGeometry (OpenGl_GUM_PREPARE, theViewId, theGlContext);
106 else if (theMode == OpenGl_GUM_PREPARE)
108 myRaytraceGeometry.ClearMaterials();
110 myArrayToTrianglesMap.clear();
112 myIsRaytraceDataValid = Standard_False;
115 // The set of processed structures (reflected to ray-tracing)
116 // This set is used to remove out-of-date records from the
117 // hash map of structures
118 std::set<const OpenGl_Structure*> anElements;
120 // Set to store all currently visible OpenGL primitive arrays
121 // applicable for ray-tracing
122 std::set<Standard_Size> anArrayIDs;
124 // Set to store all non-raytracable elements allowing tracking
125 // of changes in OpenGL scene (only for path tracing)
126 std::set<Standard_Integer> aNonRaytraceIDs;
128 const OpenGl_Layer& aLayer = myZLayers.Layer (Graphic3d_ZLayerId_Default);
130 if (aLayer.NbStructures() != 0)
132 const OpenGl_ArrayOfIndexedMapOfStructure& aStructArray = aLayer.ArrayOfStructures();
134 for (Standard_Integer anIndex = 0; anIndex < aStructArray.Length(); ++anIndex)
136 for (OpenGl_IndexedMapOfStructure::Iterator aStructIt (aStructArray (anIndex)); aStructIt.More(); aStructIt.Next())
138 const OpenGl_Structure* aStructure = aStructIt.Value();
140 if (theMode == OpenGl_GUM_CHECK)
142 if (toUpdateStructure (aStructure))
144 return updateRaytraceGeometry (OpenGl_GUM_PREPARE, theViewId, theGlContext);
146 else if (aStructure->IsVisible() && myRaytraceParameters.GlobalIllumination)
148 aNonRaytraceIDs.insert (aStructure->highlight ? aStructure->Id : -aStructure->Id);
151 else if (theMode == OpenGl_GUM_PREPARE)
153 if (!aStructure->IsRaytracable() || !aStructure->IsVisible())
157 else if (!aStructure->ViewAffinity.IsNull() && !aStructure->ViewAffinity->IsVisible (theViewId))
162 for (OpenGl_Structure::GroupIterator aGroupIter (aStructure->Groups()); aGroupIter.More(); aGroupIter.Next())
164 // Extract OpenGL elements from the group (primitives arrays)
165 for (const OpenGl_ElementNode* aNode = aGroupIter.Value()->FirstNode(); aNode != NULL; aNode = aNode->next)
167 OpenGl_PrimitiveArray* aPrimArray = dynamic_cast<OpenGl_PrimitiveArray*> (aNode->elem);
169 if (aPrimArray != NULL)
171 anArrayIDs.insert (aPrimArray->GetUID());
176 else if (theMode == OpenGl_GUM_REBUILD)
178 if (!aStructure->IsRaytracable())
182 else if (addRaytraceStructure (aStructure, theGlContext))
184 anElements.insert (aStructure); // structure was processed
191 if (theMode == OpenGl_GUM_PREPARE)
193 BVH_ObjectSet<Standard_ShortReal, 3>::BVH_ObjectList anUnchangedObjects;
195 // Filter out unchanged objects so only their transformations and materials
196 // will be updated (and newly added objects will be processed from scratch)
197 for (Standard_Integer anObjIdx = 0; anObjIdx < myRaytraceGeometry.Size(); ++anObjIdx)
199 OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
200 myRaytraceGeometry.Objects().ChangeValue (anObjIdx).operator->());
202 if (aTriangleSet == NULL)
207 if (anArrayIDs.find (aTriangleSet->AssociatedPArrayID()) != anArrayIDs.end())
209 anUnchangedObjects.Append (myRaytraceGeometry.Objects().Value (anObjIdx));
211 myArrayToTrianglesMap[aTriangleSet->AssociatedPArrayID()] = aTriangleSet;
215 myRaytraceGeometry.Objects() = anUnchangedObjects;
217 return updateRaytraceGeometry (OpenGl_GUM_REBUILD, theViewId, theGlContext);
219 else if (theMode == OpenGl_GUM_REBUILD)
221 // Actualize the hash map of structures - remove out-of-date records
222 std::map<const OpenGl_Structure*, StructState>::iterator anIter = myStructureStates.begin();
224 while (anIter != myStructureStates.end())
226 if (anElements.find (anIter->first) == anElements.end())
228 myStructureStates.erase (anIter++);
236 // Actualize OpenGL layer list state
237 myRaytraceLayerListState = myZLayers.ModificationStateOfRaytracable();
239 // Rebuild two-level acceleration structure
240 myRaytraceGeometry.ProcessAcceleration();
242 myRaytraceSceneRadius = 2.f /* scale factor */ * std::max (
243 myRaytraceGeometry.Box().CornerMin().cwiseAbs().maxComp(),
244 myRaytraceGeometry.Box().CornerMax().cwiseAbs().maxComp());
246 const BVH_Vec3f aSize = myRaytraceGeometry.Box().Size();
248 myRaytraceSceneEpsilon = Max (1.0e-6f, 1.0e-4f * aSize.Modulus());
250 return uploadRaytraceData (theGlContext);
253 if (myRaytraceParameters.GlobalIllumination)
255 Standard_Boolean toRestart =
256 aNonRaytraceIDs.size() != myNonRaytraceStructureIDs.size();
258 for (std::set<Standard_Integer>::iterator anID = aNonRaytraceIDs.begin(); anID != aNonRaytraceIDs.end() && !toRestart; ++anID)
260 if (myNonRaytraceStructureIDs.find (*anID) == myNonRaytraceStructureIDs.end())
262 toRestart = Standard_True;
271 myNonRaytraceStructureIDs = aNonRaytraceIDs;
274 return Standard_True;
277 // =======================================================================
278 // function : toUpdateStructure
279 // purpose : Checks to see if the structure is modified
280 // =======================================================================
281 Standard_Boolean OpenGl_View::toUpdateStructure (const OpenGl_Structure* theStructure)
283 if (!theStructure->IsRaytracable())
285 if (theStructure->ModificationState() > 0)
287 theStructure->ResetModificationState();
289 return Standard_True; // ray-trace element was removed - need to rebuild
292 return Standard_False; // did not contain ray-trace elements
295 std::map<const OpenGl_Structure*, StructState>::iterator aStructState = myStructureStates.find (theStructure);
297 if (aStructState == myStructureStates.end() || aStructState->second.StructureState != theStructure->ModificationState())
299 return Standard_True;
301 else if (theStructure->InstancedStructure() != NULL)
303 return aStructState->second.InstancedState != theStructure->InstancedStructure()->ModificationState();
306 return Standard_False;
309 // =======================================================================
310 // function : buildTextureTransform
311 // purpose : Constructs texture transformation matrix
312 // =======================================================================
313 void buildTextureTransform (const Handle(Graphic3d_TextureParams)& theParams, BVH_Mat4f& theMatrix)
315 theMatrix.InitIdentity();
316 if (theParams.IsNull())
322 const Graphic3d_Vec2& aScale = theParams->Scale();
324 theMatrix.ChangeValue (0, 0) *= aScale.x();
325 theMatrix.ChangeValue (1, 0) *= aScale.x();
326 theMatrix.ChangeValue (2, 0) *= aScale.x();
327 theMatrix.ChangeValue (3, 0) *= aScale.x();
329 theMatrix.ChangeValue (0, 1) *= aScale.y();
330 theMatrix.ChangeValue (1, 1) *= aScale.y();
331 theMatrix.ChangeValue (2, 1) *= aScale.y();
332 theMatrix.ChangeValue (3, 1) *= aScale.y();
335 const Graphic3d_Vec2 aTrans = -theParams->Translation();
337 theMatrix.ChangeValue (0, 3) = theMatrix.GetValue (0, 0) * aTrans.x() +
338 theMatrix.GetValue (0, 1) * aTrans.y();
340 theMatrix.ChangeValue (1, 3) = theMatrix.GetValue (1, 0) * aTrans.x() +
341 theMatrix.GetValue (1, 1) * aTrans.y();
343 theMatrix.ChangeValue (2, 3) = theMatrix.GetValue (2, 0) * aTrans.x() +
344 theMatrix.GetValue (2, 1) * aTrans.y();
347 const Standard_ShortReal aSin = std::sin (
348 -theParams->Rotation() * static_cast<Standard_ShortReal> (M_PI / 180.0));
349 const Standard_ShortReal aCos = std::cos (
350 -theParams->Rotation() * static_cast<Standard_ShortReal> (M_PI / 180.0));
352 BVH_Mat4f aRotationMat;
353 aRotationMat.SetValue (0, 0, aCos);
354 aRotationMat.SetValue (1, 1, aCos);
355 aRotationMat.SetValue (0, 1, -aSin);
356 aRotationMat.SetValue (1, 0, aSin);
358 theMatrix = theMatrix * aRotationMat;
361 // =======================================================================
362 // function : convertMaterial
363 // purpose : Creates ray-tracing material properties
364 // =======================================================================
365 OpenGl_RaytraceMaterial OpenGl_View::convertMaterial (const OpenGl_AspectFace* theAspect,
366 const Handle(OpenGl_Context)& theGlContext)
368 OpenGl_RaytraceMaterial theMaterial;
370 const Graphic3d_MaterialAspect& aSrcMat = theAspect->Aspect()->FrontMaterial();
371 const OpenGl_Vec3& aMatCol = theAspect->Aspect()->InteriorColor();
372 const bool isPhysic = aSrcMat.MaterialType (Graphic3d_MATERIAL_PHYSIC);
373 const float aShine = 128.0f * float(aSrcMat.Shininess());
376 if (aSrcMat.ReflectionMode (Graphic3d_TOR_AMBIENT))
378 const OpenGl_Vec3& aSrcAmb = isPhysic ? aSrcMat.AmbientColor() : aMatCol;
379 theMaterial.Ambient = BVH_Vec4f (aSrcAmb * (float )aSrcMat.Ambient(), 1.0f);
383 theMaterial.Ambient = THE_BLACK_COLOR;
386 // diffusion component
387 if (aSrcMat.ReflectionMode (Graphic3d_TOR_DIFFUSE))
389 const OpenGl_Vec3& aSrcDif = isPhysic ? aSrcMat.DiffuseColor() : aMatCol;
390 theMaterial.Diffuse = BVH_Vec4f (aSrcDif * (float )aSrcMat.Diffuse(), -1.0f); // -1 is no texture
394 theMaterial.Diffuse = BVH_Vec4f (THE_BLACK_COLOR.rgb(), -1.0f);
397 // specular component
398 if (aSrcMat.ReflectionMode (Graphic3d_TOR_SPECULAR))
400 const OpenGl_Vec3& aSrcSpe = aSrcMat.SpecularColor();
401 const OpenGl_Vec3& aSrcSpe2 = isPhysic ? aSrcSpe : THE_WHITE_COLOR.rgb();
402 theMaterial.Specular = BVH_Vec4f (aSrcSpe2 * (float )aSrcMat.Specular(), aShine);
404 const Standard_ShortReal aMaxRefl = Max (theMaterial.Diffuse.x() + theMaterial.Specular.x(),
405 Max (theMaterial.Diffuse.y() + theMaterial.Specular.y(),
406 theMaterial.Diffuse.z() + theMaterial.Specular.z()));
408 const Standard_ShortReal aReflectionScale = 0.75f / aMaxRefl;
410 // ignore isPhysic here
411 theMaterial.Reflection = BVH_Vec4f (aSrcSpe * (float )aSrcMat.Specular() * aReflectionScale, 0.0f);
415 theMaterial.Specular = BVH_Vec4f (THE_BLACK_COLOR.rgb(), aShine);
418 // emission component
419 if (aSrcMat.ReflectionMode (Graphic3d_TOR_EMISSION))
421 const OpenGl_Vec3& aSrcEms = isPhysic ? aSrcMat.EmissiveColor() : aMatCol;
422 theMaterial.Emission = BVH_Vec4f (aSrcEms * (float )aSrcMat.Emissive(), 1.0f);
426 theMaterial.Emission = THE_BLACK_COLOR;
429 const float anIndex = (float )aSrcMat.RefractionIndex();
430 theMaterial.Transparency = BVH_Vec4f (aSrcMat.Alpha(), aSrcMat.Transparency(),
431 anIndex == 0 ? 1.0f : anIndex,
432 anIndex == 0 ? 1.0f : 1.0f / anIndex);
434 // Serialize physically-based material properties
435 const Graphic3d_BSDF& aBSDF = aSrcMat.BSDF();
437 theMaterial.BSDF.Kc = aBSDF.Kc;
438 theMaterial.BSDF.Ks = aBSDF.Ks;
439 theMaterial.BSDF.Kd = BVH_Vec4f (aBSDF.Kd, -1.f); // no texture
440 theMaterial.BSDF.Kt = BVH_Vec4f (aBSDF.Kt, 0.f);
441 theMaterial.BSDF.Le = BVH_Vec4f (aBSDF.Le, 0.f);
443 theMaterial.BSDF.Absorption = aBSDF.Absorption;
445 theMaterial.BSDF.FresnelCoat = aBSDF.FresnelCoat.Serialize ();
446 theMaterial.BSDF.FresnelBase = aBSDF.FresnelBase.Serialize ();
448 // Handle material textures
449 if (!theAspect->Aspect()->ToMapTexture())
454 const Handle(OpenGl_TextureSet)& aTextureSet = theAspect->TextureSet (theGlContext);
455 if (aTextureSet.IsNull()
456 || aTextureSet->IsEmpty()
457 || aTextureSet->First().IsNull())
462 if (theGlContext->HasRayTracingTextures())
464 const Handle(OpenGl_Texture)& aTexture = aTextureSet->First();
465 buildTextureTransform (aTexture->Sampler()->Parameters(), theMaterial.TextureTransform);
467 // write texture ID to diffuse w-component
468 theMaterial.Diffuse.w() = theMaterial.BSDF.Kd.w() = static_cast<Standard_ShortReal> (myRaytraceGeometry.AddTexture (aTexture));
470 else if (!myIsRaytraceWarnTextures)
472 const TCollection_ExtendedString aWarnMessage =
473 "Warning: texturing in Ray-Trace requires GL_ARB_bindless_texture extension which is missing. "
474 "Please try to update graphics card driver. At the moment textures will be ignored.";
476 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
477 GL_DEBUG_TYPE_PORTABILITY, 0, GL_DEBUG_SEVERITY_HIGH, aWarnMessage);
479 myIsRaytraceWarnTextures = Standard_True;
485 // =======================================================================
486 // function : addRaytraceStructure
487 // purpose : Adds OpenGL structure to ray-traced scene geometry
488 // =======================================================================
489 Standard_Boolean OpenGl_View::addRaytraceStructure (const OpenGl_Structure* theStructure,
490 const Handle(OpenGl_Context)& theGlContext)
492 if (!theStructure->IsVisible())
494 myStructureStates[theStructure] = StructState (theStructure);
496 return Standard_True;
499 // Get structure material
500 OpenGl_RaytraceMaterial aDefaultMaterial;
501 Standard_Boolean aResult = addRaytraceGroups (theStructure, aDefaultMaterial, theStructure->Transformation(), theGlContext);
503 // Process all connected OpenGL structures
504 const OpenGl_Structure* anInstanced = theStructure->InstancedStructure();
506 if (anInstanced != NULL && anInstanced->IsRaytracable())
508 aResult &= addRaytraceGroups (anInstanced, aDefaultMaterial, theStructure->Transformation(), theGlContext);
511 myStructureStates[theStructure] = StructState (theStructure);
516 // =======================================================================
517 // function : addRaytraceGroups
518 // purpose : Adds OpenGL groups to ray-traced scene geometry
519 // =======================================================================
520 Standard_Boolean OpenGl_View::addRaytraceGroups (const OpenGl_Structure* theStructure,
521 const OpenGl_RaytraceMaterial& theStructMat,
522 const Handle(Geom_Transformation)& theTrsf,
523 const Handle(OpenGl_Context)& theGlContext)
526 for (OpenGl_Structure::GroupIterator aGroupIter (theStructure->Groups()); aGroupIter.More(); aGroupIter.Next())
528 // Get group material
529 OpenGl_RaytraceMaterial aGroupMaterial;
530 if (aGroupIter.Value()->AspectFace() != NULL)
532 aGroupMaterial = convertMaterial (
533 aGroupIter.Value()->AspectFace(), theGlContext);
536 Standard_Integer aMatID = static_cast<Standard_Integer> (myRaytraceGeometry.Materials.size());
538 // Use group material if available, otherwise use structure material
539 myRaytraceGeometry.Materials.push_back (
540 aGroupIter.Value()->AspectFace() != NULL ? aGroupMaterial : theStructMat);
542 // Add OpenGL elements from group (extract primitives arrays and aspects)
543 for (const OpenGl_ElementNode* aNode = aGroupIter.Value()->FirstNode(); aNode != NULL; aNode = aNode->next)
545 OpenGl_AspectFace* anAspect = dynamic_cast<OpenGl_AspectFace*> (aNode->elem);
547 if (anAspect != NULL)
549 aMatID = static_cast<Standard_Integer> (myRaytraceGeometry.Materials.size());
551 OpenGl_RaytraceMaterial aMaterial = convertMaterial (anAspect, theGlContext);
553 myRaytraceGeometry.Materials.push_back (aMaterial);
557 OpenGl_PrimitiveArray* aPrimArray = dynamic_cast<OpenGl_PrimitiveArray*> (aNode->elem);
559 if (aPrimArray != NULL)
561 std::map<Standard_Size, OpenGl_TriangleSet*>::iterator aSetIter = myArrayToTrianglesMap.find (aPrimArray->GetUID());
563 if (aSetIter != myArrayToTrianglesMap.end())
565 OpenGl_TriangleSet* aSet = aSetIter->second;
566 opencascade::handle<BVH_Transform<Standard_ShortReal, 4> > aTransform = new BVH_Transform<Standard_ShortReal, 4>();
567 if (!theTrsf.IsNull())
569 theTrsf->Trsf().GetMat4 (aMat4);
570 aTransform->SetTransform (aMat4);
573 aSet->SetProperties (aTransform);
574 if (aSet->MaterialIndex() != OpenGl_TriangleSet::INVALID_MATERIAL && aSet->MaterialIndex() != aMatID)
576 aSet->SetMaterialIndex (aMatID);
581 if (Handle(OpenGl_TriangleSet) aSet = addRaytracePrimitiveArray (aPrimArray, aMatID, 0))
583 opencascade::handle<BVH_Transform<Standard_ShortReal, 4> > aTransform = new BVH_Transform<Standard_ShortReal, 4>();
584 if (!theTrsf.IsNull())
586 theTrsf->Trsf().GetMat4 (aMat4);
587 aTransform->SetTransform (aMat4);
590 aSet->SetProperties (aTransform);
591 myRaytraceGeometry.Objects().Append (aSet);
599 return Standard_True;
602 // =======================================================================
603 // function : addRaytracePrimitiveArray
604 // purpose : Adds OpenGL primitive array to ray-traced scene geometry
605 // =======================================================================
606 Handle(OpenGl_TriangleSet) OpenGl_View::addRaytracePrimitiveArray (const OpenGl_PrimitiveArray* theArray,
607 const Standard_Integer theMaterial,
608 const OpenGl_Mat4* theTransform)
610 const Handle(Graphic3d_BoundBuffer)& aBounds = theArray->Bounds();
611 const Handle(Graphic3d_IndexBuffer)& anIndices = theArray->Indices();
612 const Handle(Graphic3d_Buffer)& anAttribs = theArray->Attributes();
614 if (theArray->DrawMode() < GL_TRIANGLES
615 #ifndef GL_ES_VERSION_2_0
616 || theArray->DrawMode() > GL_POLYGON
618 || theArray->DrawMode() > GL_TRIANGLE_FAN
620 || anAttribs.IsNull())
622 return Handle(OpenGl_TriangleSet)();
625 OpenGl_Mat4 aNormalMatrix;
626 if (theTransform != NULL)
628 Standard_ASSERT_RETURN (theTransform->Inverted (aNormalMatrix),
629 "Error: Failed to compute normal transformation matrix", NULL);
631 aNormalMatrix.Transpose();
634 Handle(OpenGl_TriangleSet) aSet = new OpenGl_TriangleSet (theArray->GetUID(), myRaytraceBVHBuilder);
636 aSet->Vertices.reserve (anAttribs->NbElements);
637 aSet->Normals.reserve (anAttribs->NbElements);
638 aSet->TexCrds.reserve (anAttribs->NbElements);
640 const size_t aVertFrom = aSet->Vertices.size();
641 for (Standard_Integer anAttribIter = 0; anAttribIter < anAttribs->NbAttributes; ++anAttribIter)
643 const Graphic3d_Attribute& anAttrib = anAttribs->Attribute (anAttribIter);
644 const size_t anOffset = anAttribs->AttributeOffset (anAttribIter);
645 if (anAttrib.Id == Graphic3d_TOA_POS)
647 if (anAttrib.DataType == Graphic3d_TOD_VEC3
648 || anAttrib.DataType == Graphic3d_TOD_VEC4)
650 for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
652 aSet->Vertices.push_back (
653 *reinterpret_cast<const Graphic3d_Vec3*> (anAttribs->value (aVertIter) + anOffset));
656 else if (anAttrib.DataType == Graphic3d_TOD_VEC2)
658 for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
660 const Standard_ShortReal* aCoords =
661 reinterpret_cast<const Standard_ShortReal*> (anAttribs->value (aVertIter) + anOffset);
663 aSet->Vertices.push_back (BVH_Vec3f (aCoords[0], aCoords[1], 0.0f));
667 else if (anAttrib.Id == Graphic3d_TOA_NORM)
669 if (anAttrib.DataType == Graphic3d_TOD_VEC3
670 || anAttrib.DataType == Graphic3d_TOD_VEC4)
672 for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
674 aSet->Normals.push_back (
675 *reinterpret_cast<const Graphic3d_Vec3*> (anAttribs->value (aVertIter) + anOffset));
679 else if (anAttrib.Id == Graphic3d_TOA_UV)
681 if (anAttrib.DataType == Graphic3d_TOD_VEC2)
683 for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
685 aSet->TexCrds.push_back (
686 *reinterpret_cast<const Graphic3d_Vec2*> (anAttribs->value (aVertIter) + anOffset));
692 if (aSet->Normals.size() != aSet->Vertices.size())
694 for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
696 aSet->Normals.push_back (BVH_Vec3f());
700 if (aSet->TexCrds.size() != aSet->Vertices.size())
702 for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
704 aSet->TexCrds.push_back (BVH_Vec2f());
708 if (theTransform != NULL)
710 for (size_t aVertIter = aVertFrom; aVertIter < aSet->Vertices.size(); ++aVertIter)
712 BVH_Vec3f& aVertex = aSet->Vertices[aVertIter];
714 BVH_Vec4f aTransVertex = *theTransform *
715 BVH_Vec4f (aVertex.x(), aVertex.y(), aVertex.z(), 1.f);
717 aVertex = BVH_Vec3f (aTransVertex.x(), aTransVertex.y(), aTransVertex.z());
719 for (size_t aVertIter = aVertFrom; aVertIter < aSet->Normals.size(); ++aVertIter)
721 BVH_Vec3f& aNormal = aSet->Normals[aVertIter];
723 BVH_Vec4f aTransNormal = aNormalMatrix *
724 BVH_Vec4f (aNormal.x(), aNormal.y(), aNormal.z(), 0.f);
726 aNormal = BVH_Vec3f (aTransNormal.x(), aTransNormal.y(), aTransNormal.z());
730 if (!aBounds.IsNull())
732 for (Standard_Integer aBound = 0, aBoundStart = 0; aBound < aBounds->NbBounds; ++aBound)
734 const Standard_Integer aVertNum = aBounds->Bounds[aBound];
736 if (!addRaytraceVertexIndices (*aSet, theMaterial, aVertNum, aBoundStart, *theArray))
739 return Handle(OpenGl_TriangleSet)();
742 aBoundStart += aVertNum;
747 const Standard_Integer aVertNum = !anIndices.IsNull() ? anIndices->NbElements : anAttribs->NbElements;
749 if (!addRaytraceVertexIndices (*aSet, theMaterial, aVertNum, 0, *theArray))
752 return Handle(OpenGl_TriangleSet)();
757 if (aSet->Size() != 0)
765 // =======================================================================
766 // function : addRaytraceVertexIndices
767 // purpose : Adds vertex indices to ray-traced scene geometry
768 // =======================================================================
769 Standard_Boolean OpenGl_View::addRaytraceVertexIndices (OpenGl_TriangleSet& theSet,
770 const Standard_Integer theMatID,
771 const Standard_Integer theCount,
772 const Standard_Integer theOffset,
773 const OpenGl_PrimitiveArray& theArray)
775 switch (theArray.DrawMode())
777 case GL_TRIANGLES: return addRaytraceTriangleArray (theSet, theMatID, theCount, theOffset, theArray.Indices());
778 case GL_TRIANGLE_FAN: return addRaytraceTriangleFanArray (theSet, theMatID, theCount, theOffset, theArray.Indices());
779 case GL_TRIANGLE_STRIP: return addRaytraceTriangleStripArray (theSet, theMatID, theCount, theOffset, theArray.Indices());
780 #if !defined(GL_ES_VERSION_2_0)
781 case GL_QUAD_STRIP: return addRaytraceQuadrangleStripArray (theSet, theMatID, theCount, theOffset, theArray.Indices());
782 case GL_QUADS: return addRaytraceQuadrangleArray (theSet, theMatID, theCount, theOffset, theArray.Indices());
783 case GL_POLYGON: return addRaytracePolygonArray (theSet, theMatID, theCount, theOffset, theArray.Indices());
787 return Standard_False;
790 // =======================================================================
791 // function : addRaytraceTriangleArray
792 // purpose : Adds OpenGL triangle array to ray-traced scene geometry
793 // =======================================================================
794 Standard_Boolean OpenGl_View::addRaytraceTriangleArray (OpenGl_TriangleSet& theSet,
795 const Standard_Integer theMatID,
796 const Standard_Integer theCount,
797 const Standard_Integer theOffset,
798 const Handle(Graphic3d_IndexBuffer)& theIndices)
802 return Standard_True;
805 theSet.Elements.reserve (theSet.Elements.size() + theCount / 3);
807 if (!theIndices.IsNull())
809 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; aVert += 3)
811 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0),
812 theIndices->Index (aVert + 1),
813 theIndices->Index (aVert + 2),
819 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; aVert += 3)
821 theSet.Elements.push_back (BVH_Vec4i (aVert + 0, aVert + 1, aVert + 2, theMatID));
825 return Standard_True;
828 // =======================================================================
829 // function : addRaytraceTriangleFanArray
830 // purpose : Adds OpenGL triangle fan array to ray-traced scene geometry
831 // =======================================================================
832 Standard_Boolean OpenGl_View::addRaytraceTriangleFanArray (OpenGl_TriangleSet& theSet,
833 const Standard_Integer theMatID,
834 const Standard_Integer theCount,
835 const Standard_Integer theOffset,
836 const Handle(Graphic3d_IndexBuffer)& theIndices)
840 return Standard_True;
843 theSet.Elements.reserve (theSet.Elements.size() + theCount - 2);
845 if (!theIndices.IsNull())
847 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
849 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (theOffset),
850 theIndices->Index (aVert + 1),
851 theIndices->Index (aVert + 2),
857 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
859 theSet.Elements.push_back (BVH_Vec4i (theOffset,
866 return Standard_True;
869 // =======================================================================
870 // function : addRaytraceTriangleStripArray
871 // purpose : Adds OpenGL triangle strip array to ray-traced scene geometry
872 // =======================================================================
873 Standard_Boolean OpenGl_View::addRaytraceTriangleStripArray (OpenGl_TriangleSet& theSet,
874 const Standard_Integer theMatID,
875 const Standard_Integer theCount,
876 const Standard_Integer theOffset,
877 const Handle(Graphic3d_IndexBuffer)& theIndices)
881 return Standard_True;
884 theSet.Elements.reserve (theSet.Elements.size() + theCount - 2);
886 if (!theIndices.IsNull())
888 for (Standard_Integer aVert = theOffset, aCW = 0; aVert < theOffset + theCount - 2; ++aVert, aCW = (aCW + 1) % 2)
890 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + (aCW ? 1 : 0)),
891 theIndices->Index (aVert + (aCW ? 0 : 1)),
892 theIndices->Index (aVert + 2),
898 for (Standard_Integer aVert = theOffset, aCW = 0; aVert < theOffset + theCount - 2; ++aVert, aCW = (aCW + 1) % 2)
900 theSet.Elements.push_back (BVH_Vec4i (aVert + (aCW ? 1 : 0),
901 aVert + (aCW ? 0 : 1),
907 return Standard_True;
910 // =======================================================================
911 // function : addRaytraceQuadrangleArray
912 // purpose : Adds OpenGL quad array to ray-traced scene geometry
913 // =======================================================================
914 Standard_Boolean OpenGl_View::addRaytraceQuadrangleArray (OpenGl_TriangleSet& theSet,
915 const Standard_Integer theMatID,
916 const Standard_Integer theCount,
917 const Standard_Integer theOffset,
918 const Handle(Graphic3d_IndexBuffer)& theIndices)
922 return Standard_True;
925 theSet.Elements.reserve (theSet.Elements.size() + theCount / 2);
927 if (!theIndices.IsNull())
929 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 4)
931 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0),
932 theIndices->Index (aVert + 1),
933 theIndices->Index (aVert + 2),
935 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0),
936 theIndices->Index (aVert + 2),
937 theIndices->Index (aVert + 3),
943 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 4)
945 theSet.Elements.push_back (BVH_Vec4i (aVert + 0, aVert + 1, aVert + 2,
947 theSet.Elements.push_back (BVH_Vec4i (aVert + 0, aVert + 2, aVert + 3,
952 return Standard_True;
955 // =======================================================================
956 // function : addRaytraceQuadrangleStripArray
957 // purpose : Adds OpenGL quad strip array to ray-traced scene geometry
958 // =======================================================================
959 Standard_Boolean OpenGl_View::addRaytraceQuadrangleStripArray (OpenGl_TriangleSet& theSet,
960 const Standard_Integer theMatID,
961 const Standard_Integer theCount,
962 const Standard_Integer theOffset,
963 const Handle(Graphic3d_IndexBuffer)& theIndices)
967 return Standard_True;
970 theSet.Elements.reserve (theSet.Elements.size() + 2 * theCount - 6);
972 if (!theIndices.IsNull())
974 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 2)
976 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0),
977 theIndices->Index (aVert + 1),
978 theIndices->Index (aVert + 2),
981 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 1),
982 theIndices->Index (aVert + 3),
983 theIndices->Index (aVert + 2),
989 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 2)
991 theSet.Elements.push_back (BVH_Vec4i (aVert + 0,
996 theSet.Elements.push_back (BVH_Vec4i (aVert + 1,
1003 return Standard_True;
1006 // =======================================================================
1007 // function : addRaytracePolygonArray
1008 // purpose : Adds OpenGL polygon array to ray-traced scene geometry
1009 // =======================================================================
1010 Standard_Boolean OpenGl_View::addRaytracePolygonArray (OpenGl_TriangleSet& theSet,
1011 const Standard_Integer theMatID,
1012 const Standard_Integer theCount,
1013 const Standard_Integer theOffset,
1014 const Handle(Graphic3d_IndexBuffer)& theIndices)
1018 return Standard_True;
1021 theSet.Elements.reserve (theSet.Elements.size() + theCount - 2);
1023 if (!theIndices.IsNull())
1025 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
1027 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (theOffset),
1028 theIndices->Index (aVert + 1),
1029 theIndices->Index (aVert + 2),
1035 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
1037 theSet.Elements.push_back (BVH_Vec4i (theOffset,
1044 return Standard_True;
1047 const TCollection_AsciiString OpenGl_View::ShaderSource::EMPTY_PREFIX;
1049 // =======================================================================
1050 // function : Source
1051 // purpose : Returns shader source combined with prefix
1052 // =======================================================================
1053 TCollection_AsciiString OpenGl_View::ShaderSource::Source() const
1055 const TCollection_AsciiString aVersion = "#version 140";
1057 if (myPrefix.IsEmpty())
1059 return aVersion + "\n" + mySource;
1062 return aVersion + "\n" + myPrefix + "\n" + mySource;
1065 // =======================================================================
1066 // function : LoadFromFiles
1067 // purpose : Loads shader source from specified files
1068 // =======================================================================
1069 Standard_Boolean OpenGl_View::ShaderSource::LoadFromFiles (const TCollection_AsciiString* theFileNames,
1070 const TCollection_AsciiString& thePrefix)
1074 myPrefix = thePrefix;
1076 TCollection_AsciiString aMissingFiles;
1077 for (Standard_Integer anIndex = 0; !theFileNames[anIndex].IsEmpty(); ++anIndex)
1079 OSD_File aFile (theFileNames[anIndex]);
1082 aFile.Open (OSD_ReadOnly, OSD_Protection());
1084 if (!aFile.IsOpen())
1086 if (!aMissingFiles.IsEmpty())
1088 aMissingFiles += ", ";
1090 aMissingFiles += TCollection_AsciiString("'") + theFileNames[anIndex] + "'";
1093 else if (!aMissingFiles.IsEmpty())
1099 TCollection_AsciiString aSource;
1100 aFile.Read (aSource, (Standard_Integer) aFile.Size());
1101 if (!aSource.IsEmpty())
1103 mySource += TCollection_AsciiString ("\n") + aSource;
1108 if (!aMissingFiles.IsEmpty())
1110 myError = TCollection_AsciiString("Shader files ") + aMissingFiles + " are missing or inaccessible";
1111 return Standard_False;
1113 return Standard_True;
1116 // =======================================================================
1117 // function : LoadFromStrings
1119 // =======================================================================
1120 Standard_Boolean OpenGl_View::ShaderSource::LoadFromStrings (const TCollection_AsciiString* theStrings,
1121 const TCollection_AsciiString& thePrefix)
1125 myPrefix = thePrefix;
1127 for (Standard_Integer anIndex = 0; !theStrings[anIndex].IsEmpty(); ++anIndex)
1129 TCollection_AsciiString aSource = theStrings[anIndex];
1130 if (!aSource.IsEmpty())
1132 mySource += TCollection_AsciiString ("\n") + aSource;
1135 return Standard_True;
1138 // =======================================================================
1139 // function : generateShaderPrefix
1140 // purpose : Generates shader prefix based on current ray-tracing options
1141 // =======================================================================
1142 TCollection_AsciiString OpenGl_View::generateShaderPrefix (const Handle(OpenGl_Context)& theGlContext) const
1144 TCollection_AsciiString aPrefixString =
1145 TCollection_AsciiString ("#define STACK_SIZE ") + TCollection_AsciiString (myRaytraceParameters.StackSize) + "\n" +
1146 TCollection_AsciiString ("#define NB_BOUNCES ") + TCollection_AsciiString (myRaytraceParameters.NbBounces);
1148 if (myRaytraceParameters.TransparentShadows)
1150 aPrefixString += TCollection_AsciiString ("\n#define TRANSPARENT_SHADOWS");
1153 // If OpenGL driver supports bindless textures and texturing
1154 // is actually used, activate texturing in ray-tracing mode
1155 if (myRaytraceParameters.UseBindlessTextures && theGlContext->arbTexBindless != NULL)
1157 aPrefixString += TCollection_AsciiString ("\n#define USE_TEXTURES") +
1158 TCollection_AsciiString ("\n#define MAX_TEX_NUMBER ") + TCollection_AsciiString (OpenGl_RaytraceGeometry::MAX_TEX_NUMBER);
1161 if (myRaytraceParameters.GlobalIllumination) // path tracing activated
1163 aPrefixString += TCollection_AsciiString ("\n#define PATH_TRACING");
1165 if (myRaytraceParameters.AdaptiveScreenSampling) // adaptive screen sampling requested
1167 // to activate the feature we need OpenGL 4.4 and GL_NV_shader_atomic_float extension
1168 if (theGlContext->IsGlGreaterEqual (4, 4) && theGlContext->CheckExtension ("GL_NV_shader_atomic_float"))
1170 aPrefixString += TCollection_AsciiString ("\n#define ADAPTIVE_SAMPLING") +
1171 TCollection_AsciiString ("\n#define BLOCK_SIZE ") + TCollection_AsciiString (OpenGl_TileSampler::TileSize());
1175 if (myRaytraceParameters.TwoSidedBsdfModels) // two-sided BSDFs requested
1177 aPrefixString += TCollection_AsciiString ("\n#define TWO_SIDED_BXDF");
1180 switch (myRaytraceParameters.ToneMappingMethod)
1182 case Graphic3d_ToneMappingMethod_Disabled:
1184 case Graphic3d_ToneMappingMethod_Filmic:
1185 aPrefixString += TCollection_AsciiString ("\n#define TONE_MAPPING_FILMIC");
1190 if (myRaytraceParameters.DepthOfField)
1192 aPrefixString += TCollection_AsciiString("\n#define DEPTH_OF_FIELD");
1195 return aPrefixString;
1198 // =======================================================================
1199 // function : safeFailBack
1200 // purpose : Performs safe exit when shaders initialization fails
1201 // =======================================================================
1202 Standard_Boolean OpenGl_View::safeFailBack (const TCollection_ExtendedString& theMessage,
1203 const Handle(OpenGl_Context)& theGlContext)
1205 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1206 GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, theMessage);
1208 myRaytraceInitStatus = OpenGl_RT_FAIL;
1210 releaseRaytraceResources (theGlContext);
1212 return Standard_False;
1215 // =======================================================================
1216 // function : initShader
1217 // purpose : Creates new shader object with specified source
1218 // =======================================================================
1219 Handle(OpenGl_ShaderObject) OpenGl_View::initShader (const GLenum theType,
1220 const ShaderSource& theSource,
1221 const Handle(OpenGl_Context)& theGlContext)
1223 Handle(OpenGl_ShaderObject) aShader = new OpenGl_ShaderObject (theType);
1225 if (!aShader->Create (theGlContext))
1227 const TCollection_ExtendedString aMessage = TCollection_ExtendedString ("Error: Failed to create ") +
1228 (theType == GL_VERTEX_SHADER ? "vertex" : "fragment") + " shader object";
1230 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1231 GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, aMessage);
1233 aShader->Release (theGlContext.operator->());
1235 return Handle(OpenGl_ShaderObject)();
1238 if (!aShader->LoadSource (theGlContext, theSource.Source()))
1240 const TCollection_ExtendedString aMessage = TCollection_ExtendedString ("Error: Failed to set ") +
1241 (theType == GL_VERTEX_SHADER ? "vertex" : "fragment") + " shader source";
1243 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1244 GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, aMessage);
1246 aShader->Release (theGlContext.operator->());
1248 return Handle(OpenGl_ShaderObject)();
1251 TCollection_AsciiString aBuildLog;
1253 if (!aShader->Compile (theGlContext))
1255 aShader->FetchInfoLog (theGlContext, aBuildLog);
1257 const TCollection_ExtendedString aMessage = TCollection_ExtendedString ("Error: Failed to compile ") +
1258 (theType == GL_VERTEX_SHADER ? "vertex" : "fragment") + " shader object:\n" + aBuildLog;
1260 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1261 GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, aMessage);
1263 aShader->Release (theGlContext.operator->());
1265 #ifdef RAY_TRACE_PRINT_INFO
1266 std::cout << "Shader build log:\n" << aBuildLog << "\n";
1269 return Handle(OpenGl_ShaderObject)();
1271 else if (theGlContext->caps->glslWarnings)
1273 aShader->FetchInfoLog (theGlContext, aBuildLog);
1275 if (!aBuildLog.IsEmpty() && !aBuildLog.IsEqual ("No errors.\n"))
1277 const TCollection_ExtendedString aMessage = TCollection_ExtendedString (theType == GL_VERTEX_SHADER ?
1278 "Vertex" : "Fragment") + " shader was compiled with following warnings:\n" + aBuildLog;
1280 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1281 GL_DEBUG_TYPE_PORTABILITY, 0, GL_DEBUG_SEVERITY_LOW, aMessage);
1284 #ifdef RAY_TRACE_PRINT_INFO
1285 std::cout << "Shader build log:\n" << aBuildLog << "\n";
1292 // =======================================================================
1293 // function : initProgram
1294 // purpose : Creates GLSL program from the given shader objects
1295 // =======================================================================
1296 Handle(OpenGl_ShaderProgram) OpenGl_View::initProgram (const Handle(OpenGl_Context)& theGlContext,
1297 const Handle(OpenGl_ShaderObject)& theVertShader,
1298 const Handle(OpenGl_ShaderObject)& theFragShader)
1300 Handle(OpenGl_ShaderProgram) aProgram = new OpenGl_ShaderProgram;
1302 if (!aProgram->Create (theGlContext))
1304 theVertShader->Release (theGlContext.operator->());
1306 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1307 GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, "Failed to create shader program");
1309 return Handle(OpenGl_ShaderProgram)();
1312 if (!aProgram->AttachShader (theGlContext, theVertShader)
1313 || !aProgram->AttachShader (theGlContext, theFragShader))
1315 theVertShader->Release (theGlContext.operator->());
1317 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1318 GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, "Failed to attach shader objects");
1320 return Handle(OpenGl_ShaderProgram)();
1323 aProgram->SetAttributeName (theGlContext, Graphic3d_TOA_POS, "occVertex");
1325 TCollection_AsciiString aLinkLog;
1327 if (!aProgram->Link (theGlContext))
1329 aProgram->FetchInfoLog (theGlContext, aLinkLog);
1331 const TCollection_ExtendedString aMessage = TCollection_ExtendedString (
1332 "Failed to link shader program:\n") + aLinkLog;
1334 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1335 GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, aMessage);
1337 return Handle(OpenGl_ShaderProgram)();
1339 else if (theGlContext->caps->glslWarnings)
1341 aProgram->FetchInfoLog (theGlContext, aLinkLog);
1342 if (!aLinkLog.IsEmpty() && !aLinkLog.IsEqual ("No errors.\n"))
1344 const TCollection_ExtendedString aMessage = TCollection_ExtendedString (
1345 "Shader program was linked with following warnings:\n") + aLinkLog;
1347 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1348 GL_DEBUG_TYPE_PORTABILITY, 0, GL_DEBUG_SEVERITY_LOW, aMessage);
1355 // =======================================================================
1356 // function : initRaytraceResources
1357 // purpose : Initializes OpenGL/GLSL shader programs
1358 // =======================================================================
1359 Standard_Boolean OpenGl_View::initRaytraceResources (const Handle(OpenGl_Context)& theGlContext)
1361 if (myRaytraceInitStatus == OpenGl_RT_FAIL)
1363 return Standard_False;
1366 Standard_Boolean aToRebuildShaders = Standard_False;
1368 if (myRenderParams.RebuildRayTracingShaders) // requires complete re-initialization
1370 myRaytraceInitStatus = OpenGl_RT_NONE;
1371 releaseRaytraceResources (theGlContext, Standard_True);
1372 myRenderParams.RebuildRayTracingShaders = Standard_False; // clear rebuilding flag
1375 if (myRaytraceInitStatus == OpenGl_RT_INIT)
1377 if (!myIsRaytraceDataValid)
1379 return Standard_True;
1382 const Standard_Integer aRequiredStackSize =
1383 myRaytraceGeometry.TopLevelTreeDepth() + myRaytraceGeometry.BotLevelTreeDepth();
1385 if (myRaytraceParameters.StackSize < aRequiredStackSize)
1387 myRaytraceParameters.StackSize = Max (aRequiredStackSize, THE_DEFAULT_STACK_SIZE);
1389 aToRebuildShaders = Standard_True;
1393 if (aRequiredStackSize < myRaytraceParameters.StackSize)
1395 if (myRaytraceParameters.StackSize > THE_DEFAULT_STACK_SIZE)
1397 myRaytraceParameters.StackSize = Max (aRequiredStackSize, THE_DEFAULT_STACK_SIZE);
1398 aToRebuildShaders = Standard_True;
1403 Standard_Integer aNbTilesX = 8;
1404 Standard_Integer aNbTilesY = 8;
1406 for (Standard_Integer anIdx = 0; aNbTilesX * aNbTilesY < myRenderParams.NbRayTracingTiles; ++anIdx)
1408 (anIdx % 2 == 0 ? aNbTilesX : aNbTilesY) <<= 1;
1411 if (myRenderParams.RaytracingDepth != myRaytraceParameters.NbBounces
1412 || myRenderParams.IsTransparentShadowEnabled != myRaytraceParameters.TransparentShadows
1413 || myRenderParams.IsGlobalIlluminationEnabled != myRaytraceParameters.GlobalIllumination
1414 || myRenderParams.TwoSidedBsdfModels != myRaytraceParameters.TwoSidedBsdfModels
1415 || myRaytraceGeometry.HasTextures() != myRaytraceParameters.UseBindlessTextures
1416 || aNbTilesX != myRaytraceParameters.NbTilesX
1417 || aNbTilesY != myRaytraceParameters.NbTilesY)
1419 myRaytraceParameters.NbBounces = myRenderParams.RaytracingDepth;
1420 myRaytraceParameters.TransparentShadows = myRenderParams.IsTransparentShadowEnabled;
1421 myRaytraceParameters.GlobalIllumination = myRenderParams.IsGlobalIlluminationEnabled;
1422 myRaytraceParameters.TwoSidedBsdfModels = myRenderParams.TwoSidedBsdfModels;
1423 myRaytraceParameters.UseBindlessTextures = myRaytraceGeometry.HasTextures();
1425 #ifdef RAY_TRACE_PRINT_INFO
1426 if (aNbTilesX != myRaytraceParameters.NbTilesX
1427 || aNbTilesY != myRaytraceParameters.NbTilesY)
1429 std::cout << "Number of tiles X: " << aNbTilesX << "\n";
1430 std::cout << "Number of tiles Y: " << aNbTilesY << "\n";
1434 myRaytraceParameters.NbTilesX = aNbTilesX;
1435 myRaytraceParameters.NbTilesY = aNbTilesY;
1437 aToRebuildShaders = Standard_True;
1440 if (myRenderParams.AdaptiveScreenSampling != myRaytraceParameters.AdaptiveScreenSampling)
1442 myRaytraceParameters.AdaptiveScreenSampling = myRenderParams.AdaptiveScreenSampling;
1443 if (myRenderParams.AdaptiveScreenSampling) // adaptive sampling was requested
1445 if (!theGlContext->HasRayTracingAdaptiveSampling())
1447 // disable the feature if it is not supported
1448 myRaytraceParameters.AdaptiveScreenSampling = myRenderParams.AdaptiveScreenSampling = Standard_False;
1449 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_PORTABILITY, 0, GL_DEBUG_SEVERITY_LOW,
1450 "Adaptive sampling not supported (OpenGL 4.4 or GL_NV_shader_atomic_float is missing)");
1454 aToRebuildShaders = Standard_True;
1457 const bool toEnableDof = !myCamera->IsOrthographic() && myRaytraceParameters.GlobalIllumination;
1458 if (myRaytraceParameters.DepthOfField != toEnableDof)
1460 myRaytraceParameters.DepthOfField = toEnableDof;
1461 aToRebuildShaders = Standard_True;
1464 if (myRenderParams.ToneMappingMethod != myRaytraceParameters.ToneMappingMethod)
1466 myRaytraceParameters.ToneMappingMethod = myRenderParams.ToneMappingMethod;
1467 aToRebuildShaders = true;
1470 if (aToRebuildShaders)
1472 // Reject accumulated frames
1475 // Environment map should be updated
1476 myToUpdateEnvironmentMap = Standard_True;
1478 const TCollection_AsciiString aPrefixString = generateShaderPrefix (theGlContext);
1480 #ifdef RAY_TRACE_PRINT_INFO
1481 std::cout << "GLSL prefix string:" << std::endl << aPrefixString << std::endl;
1484 myRaytraceShaderSource.SetPrefix (aPrefixString);
1485 myPostFSAAShaderSource.SetPrefix (aPrefixString);
1486 myOutImageShaderSource.SetPrefix (aPrefixString);
1488 if (!myRaytraceShader->LoadSource (theGlContext, myRaytraceShaderSource.Source())
1489 || !myPostFSAAShader->LoadSource (theGlContext, myPostFSAAShaderSource.Source())
1490 || !myOutImageShader->LoadSource (theGlContext, myOutImageShaderSource.Source()))
1492 return safeFailBack ("Failed to load source into ray-tracing fragment shaders", theGlContext);
1495 TCollection_AsciiString aLog;
1497 if (!myRaytraceShader->Compile (theGlContext)
1498 || !myPostFSAAShader->Compile (theGlContext)
1499 || !myOutImageShader->Compile (theGlContext))
1501 #ifdef RAY_TRACE_PRINT_INFO
1502 myRaytraceShader->FetchInfoLog (theGlContext, aLog);
1504 if (!aLog.IsEmpty())
1506 std::cout << "Failed to compile ray-tracing shader: " << aLog << "\n";
1509 return safeFailBack ("Failed to compile ray-tracing fragment shaders", theGlContext);
1512 myRaytraceProgram->SetAttributeName (theGlContext, Graphic3d_TOA_POS, "occVertex");
1513 myPostFSAAProgram->SetAttributeName (theGlContext, Graphic3d_TOA_POS, "occVertex");
1514 myOutImageProgram->SetAttributeName (theGlContext, Graphic3d_TOA_POS, "occVertex");
1516 if (!myRaytraceProgram->Link (theGlContext)
1517 || !myPostFSAAProgram->Link (theGlContext)
1518 || !myOutImageProgram->Link (theGlContext))
1520 #ifdef RAY_TRACE_PRINT_INFO
1521 myRaytraceProgram->FetchInfoLog (theGlContext, aLog);
1523 if (!aLog.IsEmpty())
1525 std::cout << "Failed to compile ray-tracing shader: " << aLog << "\n";
1528 return safeFailBack ("Failed to initialize vertex attributes for ray-tracing program", theGlContext);
1533 if (myRaytraceInitStatus == OpenGl_RT_NONE)
1535 myAccumFrames = 0; // accumulation should be restarted
1537 if (!theGlContext->IsGlGreaterEqual (3, 1))
1539 return safeFailBack ("Ray-tracing requires OpenGL 3.1 and higher", theGlContext);
1541 else if (!theGlContext->arbTboRGB32)
1543 return safeFailBack ("Ray-tracing requires OpenGL 4.0+ or GL_ARB_texture_buffer_object_rgb32 extension", theGlContext);
1545 else if (!theGlContext->arbFBOBlit)
1547 return safeFailBack ("Ray-tracing requires EXT_framebuffer_blit extension", theGlContext);
1550 myRaytraceParameters.NbBounces = myRenderParams.RaytracingDepth;
1552 const TCollection_AsciiString aShaderFolder = Graphic3d_ShaderProgram::ShadersFolder();
1553 if (myIsRaytraceDataValid)
1555 myRaytraceParameters.StackSize = Max (THE_DEFAULT_STACK_SIZE,
1556 myRaytraceGeometry.TopLevelTreeDepth() + myRaytraceGeometry.BotLevelTreeDepth());
1559 const TCollection_AsciiString aPrefixString = generateShaderPrefix (theGlContext);
1561 #ifdef RAY_TRACE_PRINT_INFO
1562 std::cout << "GLSL prefix string:" << std::endl << aPrefixString << std::endl;
1565 ShaderSource aBasicVertShaderSrc;
1567 if (!aShaderFolder.IsEmpty())
1569 const TCollection_AsciiString aFiles[] = { aShaderFolder + "/RaytraceBase.vs", "" };
1570 if (!aBasicVertShaderSrc.LoadFromFiles (aFiles))
1572 return safeFailBack (aBasicVertShaderSrc.ErrorDescription(), theGlContext);
1577 const TCollection_AsciiString aSrcShaders[] = { Shaders_RaytraceBase_vs, "" };
1578 aBasicVertShaderSrc.LoadFromStrings (aSrcShaders);
1583 if (!aShaderFolder.IsEmpty())
1585 const TCollection_AsciiString aFiles[] = { aShaderFolder + "/RaytraceBase.fs",
1586 aShaderFolder + "/PathtraceBase.fs",
1587 aShaderFolder + "/RaytraceRender.fs",
1589 if (!myRaytraceShaderSource.LoadFromFiles (aFiles, aPrefixString))
1591 return safeFailBack (myRaytraceShaderSource.ErrorDescription(), theGlContext);
1596 const TCollection_AsciiString aSrcShaders[] = { Shaders_RaytraceBase_fs,
1597 Shaders_PathtraceBase_fs,
1598 Shaders_RaytraceRender_fs,
1600 myRaytraceShaderSource.LoadFromStrings (aSrcShaders, aPrefixString);
1603 Handle(OpenGl_ShaderObject) aBasicVertShader = initShader (GL_VERTEX_SHADER, aBasicVertShaderSrc, theGlContext);
1604 if (aBasicVertShader.IsNull())
1606 return safeFailBack ("Failed to initialize ray-trace vertex shader", theGlContext);
1609 myRaytraceShader = initShader (GL_FRAGMENT_SHADER, myRaytraceShaderSource, theGlContext);
1610 if (myRaytraceShader.IsNull())
1612 aBasicVertShader->Release (theGlContext.operator->());
1613 return safeFailBack ("Failed to initialize ray-trace fragment shader", theGlContext);
1616 myRaytraceProgram = initProgram (theGlContext, aBasicVertShader, myRaytraceShader);
1617 if (myRaytraceProgram.IsNull())
1619 return safeFailBack ("Failed to initialize ray-trace shader program", theGlContext);
1624 if (!aShaderFolder.IsEmpty())
1626 const TCollection_AsciiString aFiles[] = { aShaderFolder + "/RaytraceBase.fs", aShaderFolder + "/RaytraceSmooth.fs", "" };
1627 if (!myPostFSAAShaderSource.LoadFromFiles (aFiles, aPrefixString))
1629 return safeFailBack (myPostFSAAShaderSource.ErrorDescription(), theGlContext);
1634 const TCollection_AsciiString aSrcShaders[] = { Shaders_RaytraceBase_fs, Shaders_RaytraceSmooth_fs, "" };
1635 myPostFSAAShaderSource.LoadFromStrings (aSrcShaders, aPrefixString);
1638 Handle(OpenGl_ShaderObject) aBasicVertShader = initShader (GL_VERTEX_SHADER, aBasicVertShaderSrc, theGlContext);
1639 if (aBasicVertShader.IsNull())
1641 return safeFailBack ("Failed to initialize FSAA vertex shader", theGlContext);
1644 myPostFSAAShader = initShader (GL_FRAGMENT_SHADER, myPostFSAAShaderSource, theGlContext);
1645 if (myPostFSAAShader.IsNull())
1647 aBasicVertShader->Release (theGlContext.operator->());
1648 return safeFailBack ("Failed to initialize FSAA fragment shader", theGlContext);
1651 myPostFSAAProgram = initProgram (theGlContext, aBasicVertShader, myPostFSAAShader);
1652 if (myPostFSAAProgram.IsNull())
1654 return safeFailBack ("Failed to initialize FSAA shader program", theGlContext);
1659 if (!aShaderFolder.IsEmpty())
1661 const TCollection_AsciiString aFiles[] = { aShaderFolder + "/Display.fs", "" };
1662 if (!myOutImageShaderSource.LoadFromFiles (aFiles, aPrefixString))
1664 return safeFailBack (myOutImageShaderSource.ErrorDescription(), theGlContext);
1669 const TCollection_AsciiString aSrcShaders[] = { Shaders_Display_fs, "" };
1670 myOutImageShaderSource.LoadFromStrings (aSrcShaders, aPrefixString);
1673 Handle(OpenGl_ShaderObject) aBasicVertShader = initShader (GL_VERTEX_SHADER, aBasicVertShaderSrc, theGlContext);
1674 if (aBasicVertShader.IsNull())
1676 return safeFailBack ("Failed to set vertex shader source", theGlContext);
1679 myOutImageShader = initShader (GL_FRAGMENT_SHADER, myOutImageShaderSource, theGlContext);
1680 if (myOutImageShader.IsNull())
1682 aBasicVertShader->Release (theGlContext.operator->());
1683 return safeFailBack ("Failed to set display fragment shader source", theGlContext);
1686 myOutImageProgram = initProgram (theGlContext, aBasicVertShader, myOutImageShader);
1687 if (myOutImageProgram.IsNull())
1689 return safeFailBack ("Failed to initialize display shader program", theGlContext);
1694 if (myRaytraceInitStatus == OpenGl_RT_NONE || aToRebuildShaders)
1696 for (Standard_Integer anIndex = 0; anIndex < 2; ++anIndex)
1698 Handle(OpenGl_ShaderProgram)& aShaderProgram =
1699 (anIndex == 0) ? myRaytraceProgram : myPostFSAAProgram;
1701 theGlContext->BindProgram (aShaderProgram);
1703 aShaderProgram->SetSampler (theGlContext,
1704 "uSceneMinPointTexture", OpenGl_RT_SceneMinPointTexture);
1705 aShaderProgram->SetSampler (theGlContext,
1706 "uSceneMaxPointTexture", OpenGl_RT_SceneMaxPointTexture);
1707 aShaderProgram->SetSampler (theGlContext,
1708 "uSceneNodeInfoTexture", OpenGl_RT_SceneNodeInfoTexture);
1709 aShaderProgram->SetSampler (theGlContext,
1710 "uGeometryVertexTexture", OpenGl_RT_GeometryVertexTexture);
1711 aShaderProgram->SetSampler (theGlContext,
1712 "uGeometryNormalTexture", OpenGl_RT_GeometryNormalTexture);
1713 aShaderProgram->SetSampler (theGlContext,
1714 "uGeometryTexCrdTexture", OpenGl_RT_GeometryTexCrdTexture);
1715 aShaderProgram->SetSampler (theGlContext,
1716 "uGeometryTriangTexture", OpenGl_RT_GeometryTriangTexture);
1717 aShaderProgram->SetSampler (theGlContext,
1718 "uSceneTransformTexture", OpenGl_RT_SceneTransformTexture);
1719 aShaderProgram->SetSampler (theGlContext,
1720 "uEnvironmentMapTexture", OpenGl_RT_EnvironmentMapTexture);
1721 aShaderProgram->SetSampler (theGlContext,
1722 "uRaytraceMaterialTexture", OpenGl_RT_RaytraceMaterialTexture);
1723 aShaderProgram->SetSampler (theGlContext,
1724 "uRaytraceLightSrcTexture", OpenGl_RT_RaytraceLightSrcTexture);
1728 aShaderProgram->SetSampler (theGlContext,
1729 "uFSAAInputTexture", OpenGl_RT_FsaaInputTexture);
1733 aShaderProgram->SetSampler (theGlContext,
1734 "uAccumTexture", OpenGl_RT_PrevAccumTexture);
1737 myUniformLocations[anIndex][OpenGl_RT_aPosition] =
1738 aShaderProgram->GetAttributeLocation (theGlContext, "occVertex");
1740 myUniformLocations[anIndex][OpenGl_RT_uOriginLB] =
1741 aShaderProgram->GetUniformLocation (theGlContext, "uOriginLB");
1742 myUniformLocations[anIndex][OpenGl_RT_uOriginRB] =
1743 aShaderProgram->GetUniformLocation (theGlContext, "uOriginRB");
1744 myUniformLocations[anIndex][OpenGl_RT_uOriginLT] =
1745 aShaderProgram->GetUniformLocation (theGlContext, "uOriginLT");
1746 myUniformLocations[anIndex][OpenGl_RT_uOriginRT] =
1747 aShaderProgram->GetUniformLocation (theGlContext, "uOriginRT");
1748 myUniformLocations[anIndex][OpenGl_RT_uDirectLB] =
1749 aShaderProgram->GetUniformLocation (theGlContext, "uDirectLB");
1750 myUniformLocations[anIndex][OpenGl_RT_uDirectRB] =
1751 aShaderProgram->GetUniformLocation (theGlContext, "uDirectRB");
1752 myUniformLocations[anIndex][OpenGl_RT_uDirectLT] =
1753 aShaderProgram->GetUniformLocation (theGlContext, "uDirectLT");
1754 myUniformLocations[anIndex][OpenGl_RT_uDirectRT] =
1755 aShaderProgram->GetUniformLocation (theGlContext, "uDirectRT");
1756 myUniformLocations[anIndex][OpenGl_RT_uViewPrMat] =
1757 aShaderProgram->GetUniformLocation (theGlContext, "uViewMat");
1758 myUniformLocations[anIndex][OpenGl_RT_uUnviewMat] =
1759 aShaderProgram->GetUniformLocation (theGlContext, "uUnviewMat");
1761 myUniformLocations[anIndex][OpenGl_RT_uSceneRad] =
1762 aShaderProgram->GetUniformLocation (theGlContext, "uSceneRadius");
1763 myUniformLocations[anIndex][OpenGl_RT_uSceneEps] =
1764 aShaderProgram->GetUniformLocation (theGlContext, "uSceneEpsilon");
1765 myUniformLocations[anIndex][OpenGl_RT_uLightCount] =
1766 aShaderProgram->GetUniformLocation (theGlContext, "uLightCount");
1767 myUniformLocations[anIndex][OpenGl_RT_uLightAmbnt] =
1768 aShaderProgram->GetUniformLocation (theGlContext, "uGlobalAmbient");
1770 myUniformLocations[anIndex][OpenGl_RT_uOffsetX] =
1771 aShaderProgram->GetUniformLocation (theGlContext, "uOffsetX");
1772 myUniformLocations[anIndex][OpenGl_RT_uOffsetY] =
1773 aShaderProgram->GetUniformLocation (theGlContext, "uOffsetY");
1774 myUniformLocations[anIndex][OpenGl_RT_uSamples] =
1775 aShaderProgram->GetUniformLocation (theGlContext, "uSamples");
1777 myUniformLocations[anIndex][OpenGl_RT_uTexSamplersArray] =
1778 aShaderProgram->GetUniformLocation (theGlContext, "uTextureSamplers");
1780 myUniformLocations[anIndex][OpenGl_RT_uShadowsEnabled] =
1781 aShaderProgram->GetUniformLocation (theGlContext, "uShadowsEnabled");
1782 myUniformLocations[anIndex][OpenGl_RT_uReflectEnabled] =
1783 aShaderProgram->GetUniformLocation (theGlContext, "uReflectEnabled");
1784 myUniformLocations[anIndex][OpenGl_RT_uSphereMapEnabled] =
1785 aShaderProgram->GetUniformLocation (theGlContext, "uSphereMapEnabled");
1786 myUniformLocations[anIndex][OpenGl_RT_uSphereMapForBack] =
1787 aShaderProgram->GetUniformLocation (theGlContext, "uSphereMapForBack");
1788 myUniformLocations[anIndex][OpenGl_RT_uBlockedRngEnabled] =
1789 aShaderProgram->GetUniformLocation (theGlContext, "uBlockedRngEnabled");
1791 myUniformLocations[anIndex][OpenGl_RT_uWinSizeX] =
1792 aShaderProgram->GetUniformLocation (theGlContext, "uWinSizeX");
1793 myUniformLocations[anIndex][OpenGl_RT_uWinSizeY] =
1794 aShaderProgram->GetUniformLocation (theGlContext, "uWinSizeY");
1796 myUniformLocations[anIndex][OpenGl_RT_uAccumSamples] =
1797 aShaderProgram->GetUniformLocation (theGlContext, "uAccumSamples");
1798 myUniformLocations[anIndex][OpenGl_RT_uFrameRndSeed] =
1799 aShaderProgram->GetUniformLocation (theGlContext, "uFrameRndSeed");
1801 myUniformLocations[anIndex][OpenGl_RT_uRenderImage] =
1802 aShaderProgram->GetUniformLocation (theGlContext, "uRenderImage");
1803 myUniformLocations[anIndex][OpenGl_RT_uOffsetImage] =
1804 aShaderProgram->GetUniformLocation (theGlContext, "uOffsetImage");
1806 myUniformLocations[anIndex][OpenGl_RT_uBackColorTop] =
1807 aShaderProgram->GetUniformLocation (theGlContext, "uBackColorTop");
1808 myUniformLocations[anIndex][OpenGl_RT_uBackColorBot] =
1809 aShaderProgram->GetUniformLocation (theGlContext, "uBackColorBot");
1811 myUniformLocations[anIndex][OpenGl_RT_uMaxRadiance] =
1812 aShaderProgram->GetUniformLocation (theGlContext, "uMaxRadiance");
1815 theGlContext->BindProgram (myOutImageProgram);
1817 myOutImageProgram->SetSampler (theGlContext,
1818 "uInputTexture", OpenGl_RT_PrevAccumTexture);
1820 myOutImageProgram->SetSampler (theGlContext,
1821 "uDepthTexture", OpenGl_RT_RaytraceDepthTexture);
1823 theGlContext->BindProgram (NULL);
1826 if (myRaytraceInitStatus != OpenGl_RT_NONE)
1828 return myRaytraceInitStatus == OpenGl_RT_INIT;
1831 const GLfloat aVertices[] = { -1.f, -1.f, 0.f,
1838 myRaytraceScreenQuad.Init (theGlContext, 3, 6, aVertices);
1840 myRaytraceInitStatus = OpenGl_RT_INIT; // initialized in normal way
1842 return Standard_True;
1845 // =======================================================================
1846 // function : nullifyResource
1847 // purpose : Releases OpenGL resource
1848 // =======================================================================
1850 inline void nullifyResource (const Handle(OpenGl_Context)& theGlContext, Handle(T)& theResource)
1852 if (!theResource.IsNull())
1854 theResource->Release (theGlContext.operator->());
1855 theResource.Nullify();
1859 // =======================================================================
1860 // function : releaseRaytraceResources
1861 // purpose : Releases OpenGL/GLSL shader programs
1862 // =======================================================================
1863 void OpenGl_View::releaseRaytraceResources (const Handle(OpenGl_Context)& theGlContext, const Standard_Boolean theToRebuild)
1865 // release shader resources
1866 nullifyResource (theGlContext, myRaytraceShader);
1867 nullifyResource (theGlContext, myPostFSAAShader);
1869 nullifyResource (theGlContext, myRaytraceProgram);
1870 nullifyResource (theGlContext, myPostFSAAProgram);
1871 nullifyResource (theGlContext, myOutImageProgram);
1873 if (!theToRebuild) // complete release
1875 myRaytraceFBO1[0]->Release (theGlContext.operator->());
1876 myRaytraceFBO1[1]->Release (theGlContext.operator->());
1877 myRaytraceFBO2[0]->Release (theGlContext.operator->());
1878 myRaytraceFBO2[1]->Release (theGlContext.operator->());
1880 nullifyResource (theGlContext, myRaytraceOutputTexture[0]);
1881 nullifyResource (theGlContext, myRaytraceOutputTexture[1]);
1883 nullifyResource (theGlContext, myRaytraceTileOffsetsTexture[0]);
1884 nullifyResource (theGlContext, myRaytraceTileOffsetsTexture[1]);
1885 nullifyResource (theGlContext, myRaytraceVisualErrorTexture[0]);
1886 nullifyResource (theGlContext, myRaytraceVisualErrorTexture[1]);
1888 nullifyResource (theGlContext, mySceneNodeInfoTexture);
1889 nullifyResource (theGlContext, mySceneMinPointTexture);
1890 nullifyResource (theGlContext, mySceneMaxPointTexture);
1892 nullifyResource (theGlContext, myGeometryVertexTexture);
1893 nullifyResource (theGlContext, myGeometryNormalTexture);
1894 nullifyResource (theGlContext, myGeometryTexCrdTexture);
1895 nullifyResource (theGlContext, myGeometryTriangTexture);
1896 nullifyResource (theGlContext, mySceneTransformTexture);
1898 nullifyResource (theGlContext, myRaytraceLightSrcTexture);
1899 nullifyResource (theGlContext, myRaytraceMaterialTexture);
1901 myRaytraceGeometry.ReleaseResources (theGlContext);
1903 if (myRaytraceScreenQuad.IsValid ())
1905 myRaytraceScreenQuad.Release (theGlContext.operator->());
1910 // =======================================================================
1911 // function : updateRaytraceBuffers
1912 // purpose : Updates auxiliary OpenGL frame buffers.
1913 // =======================================================================
1914 Standard_Boolean OpenGl_View::updateRaytraceBuffers (const Standard_Integer theSizeX,
1915 const Standard_Integer theSizeY,
1916 const Handle(OpenGl_Context)& theGlContext)
1918 // Auxiliary buffers are not used
1919 if (!myRaytraceParameters.GlobalIllumination && !myRenderParams.IsAntialiasingEnabled)
1921 myRaytraceFBO1[0]->Release (theGlContext.operator->());
1922 myRaytraceFBO2[0]->Release (theGlContext.operator->());
1923 myRaytraceFBO1[1]->Release (theGlContext.operator->());
1924 myRaytraceFBO2[1]->Release (theGlContext.operator->());
1926 return Standard_True;
1929 if (myRaytraceParameters.AdaptiveScreenSampling)
1931 const Standard_Integer aSizeX = std::max (myRaytraceParameters.NbTilesX * 64, theSizeX);
1932 const Standard_Integer aSizeY = std::max (myRaytraceParameters.NbTilesY * 64, theSizeY);
1934 myRaytraceFBO1[0]->InitLazy (theGlContext, aSizeX, aSizeY, GL_RGBA32F, myFboDepthFormat);
1935 myRaytraceFBO2[0]->InitLazy (theGlContext, aSizeX, aSizeY, GL_RGBA32F, myFboDepthFormat);
1937 if (myRaytraceFBO1[1]->IsValid()) // second FBO not needed
1939 myRaytraceFBO1[1]->Release (theGlContext.operator->());
1940 myRaytraceFBO2[1]->Release (theGlContext.operator->());
1943 else // non-adaptive mode
1945 if (myRaytraceFBO1[0]->GetSizeX() != theSizeX
1946 || myRaytraceFBO1[0]->GetSizeY() != theSizeY)
1948 myAccumFrames = 0; // accumulation should be restarted
1951 myRaytraceFBO1[0]->InitLazy (theGlContext, theSizeX, theSizeY, GL_RGBA32F, myFboDepthFormat);
1952 myRaytraceFBO2[0]->InitLazy (theGlContext, theSizeX, theSizeY, GL_RGBA32F, myFboDepthFormat);
1954 // Init second set of buffers for stereographic rendering
1955 if (myCamera->ProjectionType() == Graphic3d_Camera::Projection_Stereo)
1957 myRaytraceFBO1[1]->InitLazy (theGlContext, theSizeX, theSizeY, GL_RGBA32F, myFboDepthFormat);
1958 myRaytraceFBO2[1]->InitLazy (theGlContext, theSizeX, theSizeY, GL_RGBA32F, myFboDepthFormat);
1960 else if (myRaytraceFBO1[1]->IsValid()) // second FBO not needed
1962 myRaytraceFBO1[1]->Release (theGlContext.operator->());
1963 myRaytraceFBO2[1]->Release (theGlContext.operator->());
1967 myTileSampler.SetSize (theSizeX, theSizeY);
1969 if (myRaytraceTileOffsetsTexture[0].IsNull()
1970 || myRaytraceTileOffsetsTexture[1].IsNull())
1972 myRaytraceOutputTexture[0] = new OpenGl_Texture();
1973 myRaytraceOutputTexture[1] = new OpenGl_Texture();
1975 myRaytraceTileOffsetsTexture[0] = new OpenGl_Texture();
1976 myRaytraceTileOffsetsTexture[1] = new OpenGl_Texture();
1977 myRaytraceVisualErrorTexture[0] = new OpenGl_Texture();
1978 myRaytraceVisualErrorTexture[1] = new OpenGl_Texture();
1981 if (myRaytraceOutputTexture[0]->SizeX() / 3 != theSizeX
1982 || myRaytraceOutputTexture[0]->SizeY() / 2 != theSizeY)
1986 // Due to limitations of OpenGL image load-store extension
1987 // atomic operations are supported only for single-channel
1988 // images, so we define GL_R32F image. It is used as array
1989 // of 6D floating point vectors:
1990 // 0 - R color channel
1991 // 1 - G color channel
1992 // 2 - B color channel
1993 // 3 - hit time transformed into OpenGL NDC space
1994 // 4 - luminance accumulated for odd samples only
1995 myRaytraceOutputTexture[0]->InitRectangle (theGlContext,
1996 theSizeX * 3, theSizeY * 2, OpenGl_TextureFormat::Create<GLfloat, 1>());
1998 // workaround for some NVIDIA drivers
1999 myRaytraceVisualErrorTexture[0]->Release (theGlContext.operator->());
2000 myRaytraceTileOffsetsTexture[0]->Release (theGlContext.operator->());
2002 myRaytraceVisualErrorTexture[0]->Init (theGlContext,
2003 GL_R32I, GL_RED_INTEGER, GL_INT, myTileSampler.NbTilesX(), myTileSampler.NbTilesY(), Graphic3d_TOT_2D);
2005 myRaytraceTileOffsetsTexture[0]->Init (theGlContext,
2006 GL_RG32I, GL_RG_INTEGER, GL_INT, myTileSampler.NbTilesX(), myTileSampler.NbTilesY(), Graphic3d_TOT_2D);
2009 if (myCamera->ProjectionType() == Graphic3d_Camera::Projection_Stereo)
2011 if (myRaytraceOutputTexture[1]->SizeX() / 3 != theSizeX
2012 || myRaytraceOutputTexture[1]->SizeY() / 2 != theSizeY)
2014 myRaytraceOutputTexture[1]->InitRectangle (theGlContext,
2015 theSizeX * 3, theSizeY * 2, OpenGl_TextureFormat::Create<GLfloat, 1>());
2017 myRaytraceVisualErrorTexture[1]->Release (theGlContext.operator->());
2018 myRaytraceTileOffsetsTexture[1]->Release (theGlContext.operator->());
2020 myRaytraceVisualErrorTexture[1]->Init (theGlContext,
2021 GL_R32I, GL_RED_INTEGER, GL_INT, myTileSampler.NbTilesX(), myTileSampler.NbTilesY(), Graphic3d_TOT_2D);
2023 myRaytraceTileOffsetsTexture[1]->Init (theGlContext,
2024 GL_RG32I, GL_RG_INTEGER, GL_INT, myTileSampler.NbTilesX(), myTileSampler.NbTilesY(), Graphic3d_TOT_2D);
2029 myRaytraceOutputTexture[1]->Release (theGlContext.operator->());
2032 return Standard_True;
2035 // =======================================================================
2036 // function : updateCamera
2037 // purpose : Generates viewing rays for corners of screen quad
2038 // =======================================================================
2039 void OpenGl_View::updateCamera (const OpenGl_Mat4& theOrientation,
2040 const OpenGl_Mat4& theViewMapping,
2041 OpenGl_Vec3* theOrigins,
2042 OpenGl_Vec3* theDirects,
2043 OpenGl_Mat4& theViewPr,
2044 OpenGl_Mat4& theUnview)
2046 // compute view-projection matrix
2047 theViewPr = theViewMapping * theOrientation;
2049 // compute inverse view-projection matrix
2050 theViewPr.Inverted (theUnview);
2052 Standard_Integer aOriginIndex = 0;
2053 Standard_Integer aDirectIndex = 0;
2055 for (Standard_Integer aY = -1; aY <= 1; aY += 2)
2057 for (Standard_Integer aX = -1; aX <= 1; aX += 2)
2059 OpenGl_Vec4 aOrigin (GLfloat(aX),
2064 aOrigin = theUnview * aOrigin;
2066 aOrigin.x() = aOrigin.x() / aOrigin.w();
2067 aOrigin.y() = aOrigin.y() / aOrigin.w();
2068 aOrigin.z() = aOrigin.z() / aOrigin.w();
2070 OpenGl_Vec4 aDirect (GLfloat(aX),
2075 aDirect = theUnview * aDirect;
2077 aDirect.x() = aDirect.x() / aDirect.w();
2078 aDirect.y() = aDirect.y() / aDirect.w();
2079 aDirect.z() = aDirect.z() / aDirect.w();
2081 aDirect = aDirect - aOrigin;
2083 theOrigins[aOriginIndex++] = OpenGl_Vec3 (static_cast<GLfloat> (aOrigin.x()),
2084 static_cast<GLfloat> (aOrigin.y()),
2085 static_cast<GLfloat> (aOrigin.z()));
2087 theDirects[aDirectIndex++] = OpenGl_Vec3 (static_cast<GLfloat> (aDirect.x()),
2088 static_cast<GLfloat> (aDirect.y()),
2089 static_cast<GLfloat> (aDirect.z()));
2094 // =======================================================================
2095 // function : updatePerspCameraPT
2096 // purpose : Generates viewing rays (path tracing, perspective camera)
2097 // =======================================================================
2098 void OpenGl_View::updatePerspCameraPT (const OpenGl_Mat4& theOrientation,
2099 const OpenGl_Mat4& theViewMapping,
2100 Graphic3d_Camera::Projection theProjection,
2101 OpenGl_Mat4& theViewPr,
2102 OpenGl_Mat4& theUnview,
2103 const int theWinSizeX,
2104 const int theWinSizeY)
2106 // compute view-projection matrix
2107 theViewPr = theViewMapping * theOrientation;
2109 // compute inverse view-projection matrix
2110 theViewPr.Inverted(theUnview);
2112 // get camera stereo params
2113 float anIOD = myCamera->GetIODType() == Graphic3d_Camera::IODType_Relative
2114 ? static_cast<float> (myCamera->IOD() * myCamera->Distance())
2115 : static_cast<float> (myCamera->IOD());
2117 float aZFocus = myCamera->ZFocusType() == Graphic3d_Camera::FocusType_Relative
2118 ? static_cast<float> (myCamera->ZFocus() * myCamera->Distance())
2119 : static_cast<float> (myCamera->ZFocus());
2121 // get camera view vectors
2122 const gp_Pnt anOrig = myCamera->Eye();
2124 myEyeOrig = OpenGl_Vec3 (static_cast<float> (anOrig.X()),
2125 static_cast<float> (anOrig.Y()),
2126 static_cast<float> (anOrig.Z()));
2128 const gp_Dir aView = myCamera->Direction();
2130 OpenGl_Vec3 anEyeViewMono = OpenGl_Vec3 (static_cast<float> (aView.X()),
2131 static_cast<float> (aView.Y()),
2132 static_cast<float> (aView.Z()));
2134 const gp_Dir anUp = myCamera->Up();
2136 myEyeVert = OpenGl_Vec3 (static_cast<float> (anUp.X()),
2137 static_cast<float> (anUp.Y()),
2138 static_cast<float> (anUp.Z()));
2140 myEyeSide = OpenGl_Vec3::Cross (anEyeViewMono, myEyeVert);
2142 const double aScaleY = tan (myCamera->FOVy() / 360 * M_PI);
2143 const double aScaleX = theWinSizeX * aScaleY / theWinSizeY;
2145 myEyeSize = OpenGl_Vec2 (static_cast<float> (aScaleX),
2146 static_cast<float> (aScaleY));
2148 if (theProjection == Graphic3d_Camera::Projection_Perspective)
2150 myEyeView = anEyeViewMono;
2152 else // stereo camera
2154 // compute z-focus point
2155 OpenGl_Vec3 aZFocusPoint = myEyeOrig + anEyeViewMono * aZFocus;
2157 // compute stereo camera shift
2158 float aDx = theProjection == Graphic3d_Camera::Projection_MonoRightEye ? 0.5f * anIOD : -0.5f * anIOD;
2159 myEyeOrig += myEyeSide.Normalized() * aDx;
2161 // estimate new camera direction vector and correct its length
2162 myEyeView = (aZFocusPoint - myEyeOrig).Normalized();
2163 myEyeView *= 1.f / anEyeViewMono.Dot (myEyeView);
2167 // =======================================================================
2168 // function : uploadRaytraceData
2169 // purpose : Uploads ray-trace data to the GPU
2170 // =======================================================================
2171 Standard_Boolean OpenGl_View::uploadRaytraceData (const Handle(OpenGl_Context)& theGlContext)
2173 if (!theGlContext->IsGlGreaterEqual (3, 1))
2175 #ifdef RAY_TRACE_PRINT_INFO
2176 std::cout << "Error: OpenGL version is less than 3.1" << std::endl;
2178 return Standard_False;
2181 myAccumFrames = 0; // accumulation should be restarted
2183 /////////////////////////////////////////////////////////////////////////////
2184 // Prepare OpenGL textures
2186 if (theGlContext->arbTexBindless != NULL)
2188 // If OpenGL driver supports bindless textures we need
2189 // to get unique 64- bit handles for using on the GPU
2190 if (!myRaytraceGeometry.UpdateTextureHandles (theGlContext))
2192 #ifdef RAY_TRACE_PRINT_INFO
2193 std::cout << "Error: Failed to get OpenGL texture handles" << std::endl;
2195 return Standard_False;
2199 /////////////////////////////////////////////////////////////////////////////
2200 // Create OpenGL BVH buffers
2202 if (mySceneNodeInfoTexture.IsNull()) // create scene BVH buffers
2204 mySceneNodeInfoTexture = new OpenGl_TextureBufferArb;
2205 mySceneMinPointTexture = new OpenGl_TextureBufferArb;
2206 mySceneMaxPointTexture = new OpenGl_TextureBufferArb;
2207 mySceneTransformTexture = new OpenGl_TextureBufferArb;
2209 if (!mySceneNodeInfoTexture->Create (theGlContext)
2210 || !mySceneMinPointTexture->Create (theGlContext)
2211 || !mySceneMaxPointTexture->Create (theGlContext)
2212 || !mySceneTransformTexture->Create (theGlContext))
2214 #ifdef RAY_TRACE_PRINT_INFO
2215 std::cout << "Error: Failed to create scene BVH buffers" << std::endl;
2217 return Standard_False;
2221 if (myGeometryVertexTexture.IsNull()) // create geometry buffers
2223 myGeometryVertexTexture = new OpenGl_TextureBufferArb;
2224 myGeometryNormalTexture = new OpenGl_TextureBufferArb;
2225 myGeometryTexCrdTexture = new OpenGl_TextureBufferArb;
2226 myGeometryTriangTexture = new OpenGl_TextureBufferArb;
2228 if (!myGeometryVertexTexture->Create (theGlContext)
2229 || !myGeometryNormalTexture->Create (theGlContext)
2230 || !myGeometryTexCrdTexture->Create (theGlContext)
2231 || !myGeometryTriangTexture->Create (theGlContext))
2233 #ifdef RAY_TRACE_PRINT_INFO
2234 std::cout << "Error: Failed to create buffers for triangulation data" << std::endl;
2236 return Standard_False;
2240 if (myRaytraceMaterialTexture.IsNull()) // create material buffer
2242 myRaytraceMaterialTexture = new OpenGl_TextureBufferArb;
2244 if (!myRaytraceMaterialTexture->Create (theGlContext))
2246 #ifdef RAY_TRACE_PRINT_INFO
2247 std::cout << "Error: Failed to create buffers for material data" << std::endl;
2249 return Standard_False;
2253 /////////////////////////////////////////////////////////////////////////////
2254 // Write transform buffer
2256 BVH_Mat4f* aNodeTransforms = new BVH_Mat4f[myRaytraceGeometry.Size()];
2258 bool aResult = true;
2260 for (Standard_Integer anElemIndex = 0; anElemIndex < myRaytraceGeometry.Size(); ++anElemIndex)
2262 OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
2263 myRaytraceGeometry.Objects().ChangeValue (anElemIndex).operator->());
2265 const BVH_Transform<Standard_ShortReal, 4>* aTransform = dynamic_cast<const BVH_Transform<Standard_ShortReal, 4>* > (aTriangleSet->Properties().get());
2266 Standard_ASSERT_RETURN (aTransform != NULL,
2267 "OpenGl_TriangleSet does not contain transform", Standard_False);
2269 aNodeTransforms[anElemIndex] = aTransform->Inversed();
2272 aResult &= mySceneTransformTexture->Init (theGlContext, 4,
2273 myRaytraceGeometry.Size() * 4, reinterpret_cast<const GLfloat*> (aNodeTransforms));
2275 delete [] aNodeTransforms;
2277 /////////////////////////////////////////////////////////////////////////////
2278 // Write geometry and bottom-level BVH buffers
2280 Standard_Size aTotalVerticesNb = 0;
2281 Standard_Size aTotalElementsNb = 0;
2282 Standard_Size aTotalBVHNodesNb = 0;
2284 for (Standard_Integer anElemIndex = 0; anElemIndex < myRaytraceGeometry.Size(); ++anElemIndex)
2286 OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
2287 myRaytraceGeometry.Objects().ChangeValue (anElemIndex).operator->());
2289 Standard_ASSERT_RETURN (aTriangleSet != NULL,
2290 "Error: Failed to get triangulation of OpenGL element", Standard_False);
2292 aTotalVerticesNb += aTriangleSet->Vertices.size();
2293 aTotalElementsNb += aTriangleSet->Elements.size();
2295 Standard_ASSERT_RETURN (!aTriangleSet->QuadBVH().IsNull(),
2296 "Error: Failed to get bottom-level BVH of OpenGL element", Standard_False);
2298 aTotalBVHNodesNb += aTriangleSet->QuadBVH()->NodeInfoBuffer().size();
2301 aTotalBVHNodesNb += myRaytraceGeometry.QuadBVH()->NodeInfoBuffer().size();
2303 if (aTotalBVHNodesNb != 0)
2305 aResult &= mySceneNodeInfoTexture->Init (
2306 theGlContext, 4, GLsizei (aTotalBVHNodesNb), static_cast<const GLuint*> (NULL));
2307 aResult &= mySceneMinPointTexture->Init (
2308 theGlContext, 3, GLsizei (aTotalBVHNodesNb), static_cast<const GLfloat*> (NULL));
2309 aResult &= mySceneMaxPointTexture->Init (
2310 theGlContext, 3, GLsizei (aTotalBVHNodesNb), static_cast<const GLfloat*> (NULL));
2315 #ifdef RAY_TRACE_PRINT_INFO
2316 std::cout << "Error: Failed to upload buffers for bottom-level scene BVH" << std::endl;
2318 return Standard_False;
2321 if (aTotalElementsNb != 0)
2323 aResult &= myGeometryTriangTexture->Init (
2324 theGlContext, 4, GLsizei (aTotalElementsNb), static_cast<const GLuint*> (NULL));
2327 if (aTotalVerticesNb != 0)
2329 aResult &= myGeometryVertexTexture->Init (
2330 theGlContext, 3, GLsizei (aTotalVerticesNb), static_cast<const GLfloat*> (NULL));
2331 aResult &= myGeometryNormalTexture->Init (
2332 theGlContext, 3, GLsizei (aTotalVerticesNb), static_cast<const GLfloat*> (NULL));
2333 aResult &= myGeometryTexCrdTexture->Init (
2334 theGlContext, 2, GLsizei (aTotalVerticesNb), static_cast<const GLfloat*> (NULL));
2339 #ifdef RAY_TRACE_PRINT_INFO
2340 std::cout << "Error: Failed to upload buffers for scene geometry" << std::endl;
2342 return Standard_False;
2345 const QuadBvhHandle& aBVH = myRaytraceGeometry.QuadBVH();
2347 if (aBVH->Length() > 0)
2349 aResult &= mySceneNodeInfoTexture->SubData (theGlContext, 0, aBVH->Length(),
2350 reinterpret_cast<const GLuint*> (&aBVH->NodeInfoBuffer().front()));
2351 aResult &= mySceneMinPointTexture->SubData (theGlContext, 0, aBVH->Length(),
2352 reinterpret_cast<const GLfloat*> (&aBVH->MinPointBuffer().front()));
2353 aResult &= mySceneMaxPointTexture->SubData (theGlContext, 0, aBVH->Length(),
2354 reinterpret_cast<const GLfloat*> (&aBVH->MaxPointBuffer().front()));
2357 for (Standard_Integer aNodeIdx = 0; aNodeIdx < aBVH->Length(); ++aNodeIdx)
2359 if (!aBVH->IsOuter (aNodeIdx))
2362 OpenGl_TriangleSet* aTriangleSet = myRaytraceGeometry.TriangleSet (aNodeIdx);
2364 Standard_ASSERT_RETURN (aTriangleSet != NULL,
2365 "Error: Failed to get triangulation of OpenGL element", Standard_False);
2367 Standard_Integer aBVHOffset = myRaytraceGeometry.AccelerationOffset (aNodeIdx);
2369 Standard_ASSERT_RETURN (aBVHOffset != OpenGl_RaytraceGeometry::INVALID_OFFSET,
2370 "Error: Failed to get offset for bottom-level BVH", Standard_False);
2372 const Standard_Integer aBvhBuffersSize = aTriangleSet->QuadBVH()->Length();
2374 if (aBvhBuffersSize != 0)
2376 aResult &= mySceneNodeInfoTexture->SubData (theGlContext, aBVHOffset, aBvhBuffersSize,
2377 reinterpret_cast<const GLuint*> (&aTriangleSet->QuadBVH()->NodeInfoBuffer().front()));
2378 aResult &= mySceneMinPointTexture->SubData (theGlContext, aBVHOffset, aBvhBuffersSize,
2379 reinterpret_cast<const GLfloat*> (&aTriangleSet->QuadBVH()->MinPointBuffer().front()));
2380 aResult &= mySceneMaxPointTexture->SubData (theGlContext, aBVHOffset, aBvhBuffersSize,
2381 reinterpret_cast<const GLfloat*> (&aTriangleSet->QuadBVH()->MaxPointBuffer().front()));
2385 #ifdef RAY_TRACE_PRINT_INFO
2386 std::cout << "Error: Failed to upload buffers for bottom-level scene BVHs" << std::endl;
2388 return Standard_False;
2392 const Standard_Integer aVerticesOffset = myRaytraceGeometry.VerticesOffset (aNodeIdx);
2394 Standard_ASSERT_RETURN (aVerticesOffset != OpenGl_RaytraceGeometry::INVALID_OFFSET,
2395 "Error: Failed to get offset for triangulation vertices of OpenGL element", Standard_False);
2397 if (!aTriangleSet->Vertices.empty())
2399 aResult &= myGeometryNormalTexture->SubData (theGlContext, aVerticesOffset,
2400 GLsizei (aTriangleSet->Normals.size()), reinterpret_cast<const GLfloat*> (&aTriangleSet->Normals.front()));
2401 aResult &= myGeometryTexCrdTexture->SubData (theGlContext, aVerticesOffset,
2402 GLsizei (aTriangleSet->TexCrds.size()), reinterpret_cast<const GLfloat*> (&aTriangleSet->TexCrds.front()));
2403 aResult &= myGeometryVertexTexture->SubData (theGlContext, aVerticesOffset,
2404 GLsizei (aTriangleSet->Vertices.size()), reinterpret_cast<const GLfloat*> (&aTriangleSet->Vertices.front()));
2407 const Standard_Integer anElementsOffset = myRaytraceGeometry.ElementsOffset (aNodeIdx);
2409 Standard_ASSERT_RETURN (anElementsOffset != OpenGl_RaytraceGeometry::INVALID_OFFSET,
2410 "Error: Failed to get offset for triangulation elements of OpenGL element", Standard_False);
2412 if (!aTriangleSet->Elements.empty())
2414 aResult &= myGeometryTriangTexture->SubData (theGlContext, anElementsOffset, GLsizei (aTriangleSet->Elements.size()),
2415 reinterpret_cast<const GLuint*> (&aTriangleSet->Elements.front()));
2420 #ifdef RAY_TRACE_PRINT_INFO
2421 std::cout << "Error: Failed to upload triangulation buffers for OpenGL element" << std::endl;
2423 return Standard_False;
2427 /////////////////////////////////////////////////////////////////////////////
2428 // Write material buffer
2430 if (myRaytraceGeometry.Materials.size() != 0)
2432 aResult &= myRaytraceMaterialTexture->Init (theGlContext, 4,
2433 GLsizei (myRaytraceGeometry.Materials.size() * 19), myRaytraceGeometry.Materials.front().Packed());
2437 #ifdef RAY_TRACE_PRINT_INFO
2438 std::cout << "Error: Failed to upload material buffer" << std::endl;
2440 return Standard_False;
2444 myIsRaytraceDataValid = myRaytraceGeometry.Objects().Size() != 0;
2446 #ifdef RAY_TRACE_PRINT_INFO
2448 Standard_ShortReal aMemTrgUsed = 0.f;
2449 Standard_ShortReal aMemBvhUsed = 0.f;
2451 for (Standard_Integer anElemIdx = 0; anElemIdx < myRaytraceGeometry.Size(); ++anElemIdx)
2453 OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (myRaytraceGeometry.Objects()(anElemIdx).get());
2455 aMemTrgUsed += static_cast<Standard_ShortReal> (
2456 aTriangleSet->Vertices.size() * sizeof (BVH_Vec3f));
2457 aMemTrgUsed += static_cast<Standard_ShortReal> (
2458 aTriangleSet->Normals.size() * sizeof (BVH_Vec3f));
2459 aMemTrgUsed += static_cast<Standard_ShortReal> (
2460 aTriangleSet->TexCrds.size() * sizeof (BVH_Vec2f));
2461 aMemTrgUsed += static_cast<Standard_ShortReal> (
2462 aTriangleSet->Elements.size() * sizeof (BVH_Vec4i));
2464 aMemBvhUsed += static_cast<Standard_ShortReal> (
2465 aTriangleSet->QuadBVH()->NodeInfoBuffer().size() * sizeof (BVH_Vec4i));
2466 aMemBvhUsed += static_cast<Standard_ShortReal> (
2467 aTriangleSet->QuadBVH()->MinPointBuffer().size() * sizeof (BVH_Vec3f));
2468 aMemBvhUsed += static_cast<Standard_ShortReal> (
2469 aTriangleSet->QuadBVH()->MaxPointBuffer().size() * sizeof (BVH_Vec3f));
2472 aMemBvhUsed += static_cast<Standard_ShortReal> (
2473 myRaytraceGeometry.QuadBVH()->NodeInfoBuffer().size() * sizeof (BVH_Vec4i));
2474 aMemBvhUsed += static_cast<Standard_ShortReal> (
2475 myRaytraceGeometry.QuadBVH()->MinPointBuffer().size() * sizeof (BVH_Vec3f));
2476 aMemBvhUsed += static_cast<Standard_ShortReal> (
2477 myRaytraceGeometry.QuadBVH()->MaxPointBuffer().size() * sizeof (BVH_Vec3f));
2479 std::cout << "GPU Memory Used (Mb):\n"
2480 << "\tFor mesh: " << aMemTrgUsed / 1048576 << "\n"
2481 << "\tFor BVHs: " << aMemBvhUsed / 1048576 << "\n";
2488 // =======================================================================
2489 // function : updateRaytraceLightSources
2490 // purpose : Updates 3D scene light sources for ray-tracing
2491 // =======================================================================
2492 Standard_Boolean OpenGl_View::updateRaytraceLightSources (const OpenGl_Mat4& theInvModelView, const Handle(OpenGl_Context)& theGlContext)
2494 std::vector<OpenGl_Light> aLightSources;
2496 if (myShadingModel != Graphic3d_TOSM_NONE)
2498 aLightSources.assign (myLights.begin(), myLights.end());
2500 // move positional light sources at the front of the list
2501 std::partition (aLightSources.begin(), aLightSources.end(), IsLightPositional());
2504 // get number of 'real' (not ambient) light sources
2505 const size_t aNbLights = std::count_if (aLightSources.begin(), aLightSources.end(), IsNotAmbient());
2507 Standard_Boolean wasUpdated = myRaytraceGeometry.Sources.size () != aNbLights;
2511 myRaytraceGeometry.Sources.resize (aNbLights);
2514 myRaytraceGeometry.Ambient = BVH_Vec4f (0.f, 0.f, 0.f, 0.f);
2516 for (size_t aLightIdx = 0, aRealIdx = 0; aLightIdx < aLightSources.size(); ++aLightIdx)
2518 const OpenGl_Light& aLight = aLightSources[aLightIdx];
2520 if (aLight.Type == Graphic3d_TOLS_AMBIENT)
2522 myRaytraceGeometry.Ambient += BVH_Vec4f (aLight.Color.r() * aLight.Intensity,
2523 aLight.Color.g() * aLight.Intensity,
2524 aLight.Color.b() * aLight.Intensity,
2529 BVH_Vec4f aEmission (aLight.Color.r() * aLight.Intensity,
2530 aLight.Color.g() * aLight.Intensity,
2531 aLight.Color.b() * aLight.Intensity,
2534 BVH_Vec4f aPosition (-aLight.Direction.x(),
2535 -aLight.Direction.y(),
2536 -aLight.Direction.z(),
2539 if (aLight.Type != Graphic3d_TOLS_DIRECTIONAL)
2541 aPosition = BVH_Vec4f (static_cast<float>(aLight.Position.x()),
2542 static_cast<float>(aLight.Position.y()),
2543 static_cast<float>(aLight.Position.z()),
2546 // store smoothing radius in W-component
2547 aEmission.w() = Max (aLight.Smoothness, 0.f);
2551 // store cosine of smoothing angle in W-component
2552 aEmission.w() = cosf (Min (Max (aLight.Smoothness, 0.f), static_cast<Standard_ShortReal> (M_PI / 2.0)));
2555 if (aLight.IsHeadlight)
2557 aPosition = theInvModelView * aPosition;
2560 for (int aK = 0; aK < 4; ++aK)
2562 wasUpdated |= (aEmission[aK] != myRaytraceGeometry.Sources[aRealIdx].Emission[aK])
2563 || (aPosition[aK] != myRaytraceGeometry.Sources[aRealIdx].Position[aK]);
2568 myRaytraceGeometry.Sources[aRealIdx] = OpenGl_RaytraceLight (aEmission, aPosition);
2574 if (myRaytraceLightSrcTexture.IsNull()) // create light source buffer
2576 myRaytraceLightSrcTexture = new OpenGl_TextureBufferArb;
2579 if (myRaytraceGeometry.Sources.size() != 0 && wasUpdated)
2581 const GLfloat* aDataPtr = myRaytraceGeometry.Sources.front().Packed();
2582 if (!myRaytraceLightSrcTexture->Init (theGlContext, 4, GLsizei (myRaytraceGeometry.Sources.size() * 2), aDataPtr))
2584 #ifdef RAY_TRACE_PRINT_INFO
2585 std::cout << "Error: Failed to upload light source buffer" << std::endl;
2587 return Standard_False;
2590 myAccumFrames = 0; // accumulation should be restarted
2593 return Standard_True;
2596 // =======================================================================
2597 // function : setUniformState
2598 // purpose : Sets uniform state for the given ray-tracing shader program
2599 // =======================================================================
2600 Standard_Boolean OpenGl_View::setUniformState (const Standard_Integer theProgramId,
2601 const Standard_Integer theWinSizeX,
2602 const Standard_Integer theWinSizeY,
2603 Graphic3d_Camera::Projection theProjection,
2604 const Handle(OpenGl_Context)& theGlContext)
2606 // Get projection state
2607 OpenGl_MatrixState<Standard_ShortReal>& aCntxProjectionState = theGlContext->ProjectionState;
2609 OpenGl_Mat4 aViewPrjMat;
2610 OpenGl_Mat4 anUnviewMat;
2611 OpenGl_Vec3 aOrigins[4];
2612 OpenGl_Vec3 aDirects[4];
2614 if (myCamera->IsOrthographic()
2615 || !myRenderParams.IsGlobalIlluminationEnabled)
2617 updateCamera (myCamera->OrientationMatrixF(),
2618 aCntxProjectionState.Current(),
2626 updatePerspCameraPT (myCamera->OrientationMatrixF(),
2627 aCntxProjectionState.Current(),
2635 Handle(OpenGl_ShaderProgram)& theProgram = theProgramId == 0
2637 : myPostFSAAProgram;
2639 if (theProgram.IsNull())
2641 return Standard_False;
2644 theProgram->SetUniform(theGlContext, "uEyeOrig", myEyeOrig);
2645 theProgram->SetUniform(theGlContext, "uEyeView", myEyeView);
2646 theProgram->SetUniform(theGlContext, "uEyeVert", myEyeVert);
2647 theProgram->SetUniform(theGlContext, "uEyeSide", myEyeSide);
2648 theProgram->SetUniform(theGlContext, "uEyeSize", myEyeSize);
2650 theProgram->SetUniform(theGlContext, "uApertureRadius", myRenderParams.CameraApertureRadius);
2651 theProgram->SetUniform(theGlContext, "uFocalPlaneDist", myRenderParams.CameraFocalPlaneDist);
2654 theProgram->SetUniform (theGlContext,
2655 myUniformLocations[theProgramId][OpenGl_RT_uOriginLB], aOrigins[0]);
2656 theProgram->SetUniform (theGlContext,
2657 myUniformLocations[theProgramId][OpenGl_RT_uOriginRB], aOrigins[1]);
2658 theProgram->SetUniform (theGlContext,
2659 myUniformLocations[theProgramId][OpenGl_RT_uOriginLT], aOrigins[2]);
2660 theProgram->SetUniform (theGlContext,
2661 myUniformLocations[theProgramId][OpenGl_RT_uOriginRT], aOrigins[3]);
2662 theProgram->SetUniform (theGlContext,
2663 myUniformLocations[theProgramId][OpenGl_RT_uDirectLB], aDirects[0]);
2664 theProgram->SetUniform (theGlContext,
2665 myUniformLocations[theProgramId][OpenGl_RT_uDirectRB], aDirects[1]);
2666 theProgram->SetUniform (theGlContext,
2667 myUniformLocations[theProgramId][OpenGl_RT_uDirectLT], aDirects[2]);
2668 theProgram->SetUniform (theGlContext,
2669 myUniformLocations[theProgramId][OpenGl_RT_uDirectRT], aDirects[3]);
2670 theProgram->SetUniform (theGlContext,
2671 myUniformLocations[theProgramId][OpenGl_RT_uViewPrMat], aViewPrjMat);
2672 theProgram->SetUniform (theGlContext,
2673 myUniformLocations[theProgramId][OpenGl_RT_uUnviewMat], anUnviewMat);
2675 // Set screen dimensions
2676 myRaytraceProgram->SetUniform (theGlContext,
2677 myUniformLocations[theProgramId][OpenGl_RT_uWinSizeX], theWinSizeX);
2678 myRaytraceProgram->SetUniform (theGlContext,
2679 myUniformLocations[theProgramId][OpenGl_RT_uWinSizeY], theWinSizeY);
2681 // Set 3D scene parameters
2682 theProgram->SetUniform (theGlContext,
2683 myUniformLocations[theProgramId][OpenGl_RT_uSceneRad], myRaytraceSceneRadius);
2684 theProgram->SetUniform (theGlContext,
2685 myUniformLocations[theProgramId][OpenGl_RT_uSceneEps], myRaytraceSceneEpsilon);
2687 // Set light source parameters
2688 const Standard_Integer aLightSourceBufferSize =
2689 static_cast<Standard_Integer> (myRaytraceGeometry.Sources.size());
2691 theProgram->SetUniform (theGlContext,
2692 myUniformLocations[theProgramId][OpenGl_RT_uLightCount], aLightSourceBufferSize);
2694 // Set array of 64-bit texture handles
2695 if (theGlContext->arbTexBindless != NULL && myRaytraceGeometry.HasTextures())
2697 const std::vector<GLuint64>& aTextures = myRaytraceGeometry.TextureHandles();
2699 theProgram->SetUniform (theGlContext, myUniformLocations[theProgramId][OpenGl_RT_uTexSamplersArray],
2700 static_cast<GLsizei> (aTextures.size()), reinterpret_cast<const OpenGl_Vec2u*> (&aTextures.front()));
2703 // Set background colors (only gradient background supported)
2704 if (myBgGradientArray != NULL && myBgGradientArray->IsDefined())
2706 theProgram->SetUniform (theGlContext,
2707 myUniformLocations[theProgramId][OpenGl_RT_uBackColorTop], myBgGradientArray->GradientColor (0));
2708 theProgram->SetUniform (theGlContext,
2709 myUniformLocations[theProgramId][OpenGl_RT_uBackColorBot], myBgGradientArray->GradientColor (1));
2713 const OpenGl_Vec4& aBackColor = myBgColor;
2715 theProgram->SetUniform (theGlContext,
2716 myUniformLocations[theProgramId][OpenGl_RT_uBackColorTop], aBackColor);
2717 theProgram->SetUniform (theGlContext,
2718 myUniformLocations[theProgramId][OpenGl_RT_uBackColorBot], aBackColor);
2721 // Set environment map parameters
2722 const Standard_Boolean toDisableEnvironmentMap = myTextureEnv.IsNull()
2723 || myTextureEnv->IsEmpty()
2724 || !myTextureEnv->First()->IsValid();
2726 theProgram->SetUniform (theGlContext,
2727 myUniformLocations[theProgramId][OpenGl_RT_uSphereMapEnabled], toDisableEnvironmentMap ? 0 : 1);
2729 theProgram->SetUniform (theGlContext,
2730 myUniformLocations[theProgramId][OpenGl_RT_uSphereMapForBack], myRenderParams.UseEnvironmentMapBackground ? 1 : 0);
2732 if (myRenderParams.IsGlobalIlluminationEnabled) // GI parameters
2734 theProgram->SetUniform (theGlContext,
2735 myUniformLocations[theProgramId][OpenGl_RT_uMaxRadiance], myRenderParams.RadianceClampingValue);
2737 theProgram->SetUniform (theGlContext,
2738 myUniformLocations[theProgramId][OpenGl_RT_uBlockedRngEnabled], myRenderParams.CoherentPathTracingMode ? 1 : 0);
2740 // Check whether we should restart accumulation for run-time parameters
2741 if (myRenderParams.RadianceClampingValue != myRaytraceParameters.RadianceClampingValue
2742 || myRenderParams.UseEnvironmentMapBackground != myRaytraceParameters.UseEnvMapForBackground)
2744 myAccumFrames = 0; // accumulation should be restarted
2746 myRaytraceParameters.RadianceClampingValue = myRenderParams.RadianceClampingValue;
2747 myRaytraceParameters.UseEnvMapForBackground = myRenderParams.UseEnvironmentMapBackground;
2750 else // RT parameters
2752 // Set ambient light source
2753 theProgram->SetUniform (theGlContext,
2754 myUniformLocations[theProgramId][OpenGl_RT_uLightAmbnt], myRaytraceGeometry.Ambient);
2756 // Enable/disable run-time ray-tracing effects
2757 theProgram->SetUniform (theGlContext,
2758 myUniformLocations[theProgramId][OpenGl_RT_uShadowsEnabled], myRenderParams.IsShadowEnabled ? 1 : 0);
2759 theProgram->SetUniform (theGlContext,
2760 myUniformLocations[theProgramId][OpenGl_RT_uReflectEnabled], myRenderParams.IsReflectionEnabled ? 1 : 0);
2763 return Standard_True;
2766 // =======================================================================
2767 // function : bindRaytraceTextures
2768 // purpose : Binds ray-trace textures to corresponding texture units
2769 // =======================================================================
2770 void OpenGl_View::bindRaytraceTextures (const Handle(OpenGl_Context)& theGlContext)
2772 if (myRaytraceParameters.AdaptiveScreenSampling)
2774 #if !defined(GL_ES_VERSION_2_0)
2775 theGlContext->core42->glBindImageTexture (OpenGl_RT_OutputImageLft,
2776 myRaytraceOutputTexture[0]->TextureId(), 0, GL_TRUE, 0, GL_READ_WRITE, GL_R32F);
2777 theGlContext->core42->glBindImageTexture (OpenGl_RT_OutputImageRgh,
2778 myRaytraceOutputTexture[1]->TextureId(), 0, GL_TRUE, 0, GL_READ_WRITE, GL_R32F);
2780 theGlContext->core42->glBindImageTexture (OpenGl_RT_VisualErrorImageLft,
2781 myRaytraceVisualErrorTexture[0]->TextureId(), 0, GL_TRUE, 0, GL_READ_WRITE, GL_R32I);
2782 theGlContext->core42->glBindImageTexture (OpenGl_RT_VisualErrorImageRgh,
2783 myRaytraceVisualErrorTexture[1]->TextureId(), 0, GL_TRUE, 0, GL_READ_WRITE, GL_R32I);
2784 theGlContext->core42->glBindImageTexture (OpenGl_RT_TileOffsetsImageLft,
2785 myRaytraceTileOffsetsTexture[0]->TextureId(), 0, GL_TRUE, 0, GL_READ_ONLY, GL_RG32I);
2786 theGlContext->core42->glBindImageTexture (OpenGl_RT_TileOffsetsImageRgh,
2787 myRaytraceTileOffsetsTexture[1]->TextureId(), 0, GL_TRUE, 0, GL_READ_ONLY, GL_RG32I);
2791 if (!myTextureEnv.IsNull()
2792 && !myTextureEnv->IsEmpty()
2793 && myTextureEnv->First()->IsValid())
2795 myTextureEnv->First()->Bind (theGlContext, OpenGl_RT_EnvironmentMapTexture);
2798 mySceneMinPointTexture ->BindTexture (theGlContext, OpenGl_RT_SceneMinPointTexture);
2799 mySceneMaxPointTexture ->BindTexture (theGlContext, OpenGl_RT_SceneMaxPointTexture);
2800 mySceneNodeInfoTexture ->BindTexture (theGlContext, OpenGl_RT_SceneNodeInfoTexture);
2801 myGeometryVertexTexture ->BindTexture (theGlContext, OpenGl_RT_GeometryVertexTexture);
2802 myGeometryNormalTexture ->BindTexture (theGlContext, OpenGl_RT_GeometryNormalTexture);
2803 myGeometryTexCrdTexture ->BindTexture (theGlContext, OpenGl_RT_GeometryTexCrdTexture);
2804 myGeometryTriangTexture ->BindTexture (theGlContext, OpenGl_RT_GeometryTriangTexture);
2805 mySceneTransformTexture ->BindTexture (theGlContext, OpenGl_RT_SceneTransformTexture);
2806 myRaytraceMaterialTexture->BindTexture (theGlContext, OpenGl_RT_RaytraceMaterialTexture);
2807 myRaytraceLightSrcTexture->BindTexture (theGlContext, OpenGl_RT_RaytraceLightSrcTexture);
2810 // =======================================================================
2811 // function : unbindRaytraceTextures
2812 // purpose : Unbinds ray-trace textures from corresponding texture units
2813 // =======================================================================
2814 void OpenGl_View::unbindRaytraceTextures (const Handle(OpenGl_Context)& theGlContext)
2816 mySceneMinPointTexture ->UnbindTexture (theGlContext, OpenGl_RT_SceneMinPointTexture);
2817 mySceneMaxPointTexture ->UnbindTexture (theGlContext, OpenGl_RT_SceneMaxPointTexture);
2818 mySceneNodeInfoTexture ->UnbindTexture (theGlContext, OpenGl_RT_SceneNodeInfoTexture);
2819 myGeometryVertexTexture ->UnbindTexture (theGlContext, OpenGl_RT_GeometryVertexTexture);
2820 myGeometryNormalTexture ->UnbindTexture (theGlContext, OpenGl_RT_GeometryNormalTexture);
2821 myGeometryTexCrdTexture ->UnbindTexture (theGlContext, OpenGl_RT_GeometryTexCrdTexture);
2822 myGeometryTriangTexture ->UnbindTexture (theGlContext, OpenGl_RT_GeometryTriangTexture);
2823 mySceneTransformTexture ->UnbindTexture (theGlContext, OpenGl_RT_SceneTransformTexture);
2824 myRaytraceMaterialTexture->UnbindTexture (theGlContext, OpenGl_RT_RaytraceMaterialTexture);
2825 myRaytraceLightSrcTexture->UnbindTexture (theGlContext, OpenGl_RT_RaytraceLightSrcTexture);
2827 theGlContext->core15fwd->glActiveTexture (GL_TEXTURE0);
2830 // =======================================================================
2831 // function : runRaytraceShaders
2832 // purpose : Runs ray-tracing shader programs
2833 // =======================================================================
2834 Standard_Boolean OpenGl_View::runRaytraceShaders (const Standard_Integer theSizeX,
2835 const Standard_Integer theSizeY,
2836 Graphic3d_Camera::Projection theProjection,
2837 OpenGl_FrameBuffer* theReadDrawFbo,
2838 const Handle(OpenGl_Context)& theGlContext)
2840 Standard_Boolean aResult = theGlContext->BindProgram (myRaytraceProgram);
2842 aResult &= setUniformState (0,
2848 if (myRaytraceParameters.GlobalIllumination) // path tracing
2850 aResult &= runPathtrace (theSizeX, theSizeY, theProjection, theReadDrawFbo, theGlContext);
2852 else // Whitted-style ray-tracing
2854 aResult &= runRaytrace (theSizeX, theSizeY, theProjection, theReadDrawFbo, theGlContext);
2860 // =======================================================================
2861 // function : runRaytrace
2862 // purpose : Runs Whitted-style ray-tracing
2863 // =======================================================================
2864 Standard_Boolean OpenGl_View::runRaytrace (const Standard_Integer theSizeX,
2865 const Standard_Integer theSizeY,
2866 Graphic3d_Camera::Projection theProjection,
2867 OpenGl_FrameBuffer* theReadDrawFbo,
2868 const Handle(OpenGl_Context)& theGlContext)
2870 Standard_Boolean aResult = Standard_True;
2872 bindRaytraceTextures (theGlContext);
2874 Handle(OpenGl_FrameBuffer) aRenderImageFramebuffer;
2875 Handle(OpenGl_FrameBuffer) aDepthSourceFramebuffer;
2877 // Choose proper set of frame buffers for stereo rendering
2878 const Standard_Integer aFBOIdx (theProjection == Graphic3d_Camera::Projection_MonoRightEye);
2880 if (myRenderParams.IsAntialiasingEnabled) // if second FSAA pass is used
2882 myRaytraceFBO1[aFBOIdx]->BindBuffer (theGlContext);
2884 glClear (GL_DEPTH_BUFFER_BIT); // render the image with depth
2887 theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
2889 if (myRenderParams.IsAntialiasingEnabled)
2891 glDisable (GL_DEPTH_TEST); // improve jagged edges without depth buffer
2893 // bind ray-tracing output image as input
2894 myRaytraceFBO1[aFBOIdx]->ColorTexture()->Bind (theGlContext, OpenGl_RT_FsaaInputTexture);
2896 aResult &= theGlContext->BindProgram (myPostFSAAProgram);
2898 aResult &= setUniformState (1 /* FSAA ID */,
2904 // Perform multi-pass adaptive FSAA using ping-pong technique.
2905 // We use 'FLIPTRI' sampling pattern changing for every pixel
2906 // (3 additional samples per pixel, the 1st sample is already
2907 // available from initial ray-traced image).
2908 for (Standard_Integer anIt = 1; anIt < 4; ++anIt)
2910 GLfloat aOffsetX = 1.f / theSizeX;
2911 GLfloat aOffsetY = 1.f / theSizeY;
2929 aResult &= myPostFSAAProgram->SetUniform (theGlContext,
2930 myUniformLocations[1][OpenGl_RT_uSamples], anIt + 1);
2931 aResult &= myPostFSAAProgram->SetUniform (theGlContext,
2932 myUniformLocations[1][OpenGl_RT_uOffsetX], aOffsetX);
2933 aResult &= myPostFSAAProgram->SetUniform (theGlContext,
2934 myUniformLocations[1][OpenGl_RT_uOffsetY], aOffsetY);
2936 Handle(OpenGl_FrameBuffer)& aFramebuffer = anIt % 2
2937 ? myRaytraceFBO2[aFBOIdx]
2938 : myRaytraceFBO1[aFBOIdx];
2940 aFramebuffer->BindBuffer (theGlContext);
2942 // perform adaptive FSAA pass
2943 theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
2945 aFramebuffer->ColorTexture()->Bind (theGlContext, OpenGl_RT_FsaaInputTexture);
2948 aRenderImageFramebuffer = myRaytraceFBO2[aFBOIdx];
2949 aDepthSourceFramebuffer = myRaytraceFBO1[aFBOIdx];
2951 glEnable (GL_DEPTH_TEST);
2953 // Display filtered image
2954 theGlContext->BindProgram (myOutImageProgram);
2956 if (theReadDrawFbo != NULL)
2958 theReadDrawFbo->BindBuffer (theGlContext);
2962 aRenderImageFramebuffer->UnbindBuffer (theGlContext);
2965 aRenderImageFramebuffer->ColorTexture() ->Bind (theGlContext, OpenGl_RT_PrevAccumTexture);
2966 aDepthSourceFramebuffer->DepthStencilTexture()->Bind (theGlContext, OpenGl_RT_RaytraceDepthTexture);
2968 // copy the output image with depth values
2969 theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
2971 aDepthSourceFramebuffer->DepthStencilTexture()->Unbind (theGlContext, OpenGl_RT_RaytraceDepthTexture);
2972 aRenderImageFramebuffer->ColorTexture() ->Unbind (theGlContext, OpenGl_RT_PrevAccumTexture);
2975 unbindRaytraceTextures (theGlContext);
2977 theGlContext->BindProgram (NULL);
2982 // =======================================================================
2983 // function : runPathtrace
2984 // purpose : Runs path tracing shader
2985 // =======================================================================
2986 Standard_Boolean OpenGl_View::runPathtrace (const Standard_Integer theSizeX,
2987 const Standard_Integer theSizeY,
2988 const Graphic3d_Camera::Projection theProjection,
2989 OpenGl_FrameBuffer* theReadDrawFbo,
2990 const Handle(OpenGl_Context)& theGlContext)
2992 Standard_Boolean aResult = Standard_True;
2994 if (myToUpdateEnvironmentMap) // check whether the map was changed
2996 myAccumFrames = myToUpdateEnvironmentMap = 0;
2999 if (myRenderParams.CameraApertureRadius != myPrevCameraApertureRadius
3000 || myRenderParams.CameraFocalPlaneDist != myPrevCameraFocalPlaneDist)
3003 myPrevCameraApertureRadius = myRenderParams.CameraApertureRadius;
3004 myPrevCameraFocalPlaneDist = myRenderParams.CameraFocalPlaneDist;
3009 // Choose proper set of frame buffers for stereo rendering
3010 const Standard_Integer aFBOIdx (theProjection == Graphic3d_Camera::Projection_MonoRightEye);
3012 if (myRaytraceParameters.AdaptiveScreenSampling)
3014 if (myAccumFrames == 0)
3016 myTileSampler.Reset(); // reset tile sampler to its initial state
3018 // Adaptive sampling is starting at the second frame
3019 myTileSampler.Upload (theGlContext,
3020 myRaytraceTileOffsetsTexture[aFBOIdx],
3021 myRaytraceParameters.NbTilesX,
3022 myRaytraceParameters.NbTilesY,
3027 bindRaytraceTextures (theGlContext);
3029 Handle(OpenGl_FrameBuffer) aRenderImageFramebuffer;
3030 Handle(OpenGl_FrameBuffer) aDepthSourceFramebuffer;
3031 Handle(OpenGl_FrameBuffer) anAccumImageFramebuffer;
3033 const Standard_Integer anImageId = (aFBOIdx != 0)
3034 ? OpenGl_RT_OutputImageRgh
3035 : OpenGl_RT_OutputImageLft;
3037 const Standard_Integer anErrorId = (aFBOIdx != 0)
3038 ? OpenGl_RT_VisualErrorImageRgh
3039 : OpenGl_RT_VisualErrorImageLft;
3041 const Standard_Integer anOffsetId = (aFBOIdx != 0)
3042 ? OpenGl_RT_TileOffsetsImageRgh
3043 : OpenGl_RT_TileOffsetsImageLft;
3045 aRenderImageFramebuffer = myAccumFrames % 2 ? myRaytraceFBO1[aFBOIdx] : myRaytraceFBO2[aFBOIdx];
3046 anAccumImageFramebuffer = myAccumFrames % 2 ? myRaytraceFBO2[aFBOIdx] : myRaytraceFBO1[aFBOIdx];
3048 aDepthSourceFramebuffer = aRenderImageFramebuffer;
3050 anAccumImageFramebuffer->ColorTexture()->Bind (theGlContext, OpenGl_RT_PrevAccumTexture);
3052 aRenderImageFramebuffer->BindBuffer (theGlContext);
3054 if (myAccumFrames == 0)
3056 myRNG.SetSeed(); // start RNG from beginning
3059 // Clear adaptive screen sampling images
3060 if (myRaytraceParameters.AdaptiveScreenSampling)
3062 #if !defined(GL_ES_VERSION_2_0)
3063 if (myAccumFrames == 0 || (myAccumFrames == 1 && myCamera->IsStereo()))
3065 theGlContext->core44->glClearTexImage (myRaytraceOutputTexture[aFBOIdx]->TextureId(), 0, GL_RED, GL_FLOAT, NULL);
3068 theGlContext->core44->glClearTexImage (myRaytraceVisualErrorTexture[aFBOIdx]->TextureId(), 0, GL_RED_INTEGER, GL_INT, NULL);
3072 // Set frame accumulation weight
3073 myRaytraceProgram->SetUniform (theGlContext,
3074 myUniformLocations[0][OpenGl_RT_uAccumSamples], myAccumFrames);
3076 // Set random number generator seed
3077 myRaytraceProgram->SetUniform (theGlContext,
3078 myUniformLocations[0][OpenGl_RT_uFrameRndSeed], static_cast<Standard_Integer> (myRNG.NextInt() >> 2));
3080 // Set image uniforms for render program
3081 myRaytraceProgram->SetUniform (theGlContext,
3082 myUniformLocations[0][OpenGl_RT_uRenderImage], anImageId);
3083 myRaytraceProgram->SetUniform (theGlContext,
3084 myUniformLocations[0][OpenGl_RT_uOffsetImage], anOffsetId);
3086 glDisable (GL_DEPTH_TEST);
3088 if (myRaytraceParameters.AdaptiveScreenSampling
3089 && ((myAccumFrames > 0 && !myCamera->IsStereo()) || myAccumFrames > 1))
3093 myTileSampler.TileSize() * myRaytraceParameters.NbTilesX,
3094 myTileSampler.TileSize() * myRaytraceParameters.NbTilesY);
3097 // Generate for the given RNG seed
3098 theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
3100 if (myRaytraceParameters.AdaptiveScreenSampling
3101 && ((myAccumFrames > 0 && !myCamera->IsStereo()) || myAccumFrames > 1))
3109 // Output accumulated path traced image
3110 theGlContext->BindProgram (myOutImageProgram);
3112 if (myRaytraceParameters.AdaptiveScreenSampling)
3114 // Set uniforms for display program
3115 myOutImageProgram->SetUniform (theGlContext, "uRenderImage", anImageId);
3116 myOutImageProgram->SetUniform (theGlContext, "uAccumFrames", myAccumFrames);
3117 myOutImageProgram->SetUniform (theGlContext, "uVarianceImage", anErrorId);
3118 myOutImageProgram->SetUniform (theGlContext, "uDebugAdaptive", myRenderParams.ShowSamplingTiles ? 1 : 0);
3121 if (myRaytraceParameters.GlobalIllumination)
3123 myOutImageProgram->SetUniform(theGlContext, "uExposure", myRenderParams.Exposure);
3124 switch (myRaytraceParameters.ToneMappingMethod)
3126 case Graphic3d_ToneMappingMethod_Disabled:
3128 case Graphic3d_ToneMappingMethod_Filmic:
3129 myOutImageProgram->SetUniform (theGlContext, "uWhitePoint", myRenderParams.WhitePoint);
3134 if (theReadDrawFbo != NULL)
3136 theReadDrawFbo->BindBuffer (theGlContext);
3140 aRenderImageFramebuffer->UnbindBuffer (theGlContext);
3143 aRenderImageFramebuffer->ColorTexture()->Bind (theGlContext, OpenGl_RT_PrevAccumTexture);
3145 glEnable (GL_DEPTH_TEST);
3147 // Copy accumulated image with correct depth values
3148 theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
3150 aRenderImageFramebuffer->ColorTexture()->Unbind (theGlContext, OpenGl_RT_PrevAccumTexture);
3152 if (myRaytraceParameters.AdaptiveScreenSampling)
3154 myRaytraceVisualErrorTexture[aFBOIdx]->Bind (theGlContext);
3156 // Download visual error map from the GPU and build
3157 // adjusted tile offsets for optimal image sampling
3158 myTileSampler.GrabVarianceMap (theGlContext);
3160 myTileSampler.Upload (theGlContext,
3161 myRaytraceTileOffsetsTexture[aFBOIdx],
3162 myRaytraceParameters.NbTilesX,
3163 myRaytraceParameters.NbTilesY,
3167 unbindRaytraceTextures (theGlContext);
3169 theGlContext->BindProgram (NULL);
3174 // =======================================================================
3175 // function : raytrace
3176 // purpose : Redraws the window using OpenGL/GLSL ray-tracing
3177 // =======================================================================
3178 Standard_Boolean OpenGl_View::raytrace (const Standard_Integer theSizeX,
3179 const Standard_Integer theSizeY,
3180 Graphic3d_Camera::Projection theProjection,
3181 OpenGl_FrameBuffer* theReadDrawFbo,
3182 const Handle(OpenGl_Context)& theGlContext)
3184 if (!initRaytraceResources (theGlContext))
3186 return Standard_False;
3189 if (!updateRaytraceBuffers (theSizeX, theSizeY, theGlContext))
3191 return Standard_False;
3194 OpenGl_Mat4 aLightSourceMatrix;
3196 // Get inversed model-view matrix for transforming lights
3197 myCamera->OrientationMatrixF().Inverted (aLightSourceMatrix);
3199 if (!updateRaytraceLightSources (aLightSourceMatrix, theGlContext))
3201 return Standard_False;
3204 // Generate image using Whitted-style ray-tracing or path tracing
3205 if (myIsRaytraceDataValid)
3207 myRaytraceScreenQuad.BindVertexAttrib (theGlContext, Graphic3d_TOA_POS);
3209 if (!myRaytraceGeometry.AcquireTextures (theGlContext))
3211 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR,
3212 0, GL_DEBUG_SEVERITY_MEDIUM, "Error: Failed to acquire OpenGL image textures");
3215 glDisable (GL_BLEND);
3217 const Standard_Boolean aResult = runRaytraceShaders (theSizeX,
3225 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR,
3226 0, GL_DEBUG_SEVERITY_MEDIUM, "Error: Failed to execute ray-tracing shaders");
3229 if (!myRaytraceGeometry.ReleaseTextures (theGlContext))
3231 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR,
3232 0, GL_DEBUG_SEVERITY_MEDIUM, "Error: Failed to release OpenGL image textures");
3235 myRaytraceScreenQuad.UnbindVertexAttrib (theGlContext, Graphic3d_TOA_POS);
3238 return Standard_True;