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 using namespace OpenGl_Raytrace;
27 //! Use this macro to output ray-tracing debug info
28 // #define RAY_TRACE_PRINT_INFO
30 #ifdef RAY_TRACE_PRINT_INFO
31 #include <OSD_Timer.hxx>
36 static const OpenGl_Vec4 THE_WHITE_COLOR (1.0f, 1.0f, 1.0f, 1.0f);
37 static const OpenGl_Vec4 THE_BLACK_COLOR (0.0f, 0.0f, 0.0f, 1.0f);
40 // =======================================================================
41 // function : updateRaytraceGeometry
42 // purpose : Updates 3D scene geometry for ray-tracing
43 // =======================================================================
44 Standard_Boolean OpenGl_View::updateRaytraceGeometry (const RaytraceUpdateMode theMode,
45 const Standard_Integer theViewId,
46 const Handle(OpenGl_Context)& theGlContext)
48 // In 'check' mode (OpenGl_GUM_CHECK) the scene geometry is analyzed for
49 // modifications. This is light-weight procedure performed on each frame
50 if (theMode == OpenGl_GUM_CHECK)
52 if (myLayerListState != myZLayers.ModificationState())
54 return updateRaytraceGeometry (OpenGl_GUM_PREPARE, theViewId, theGlContext);
57 else if (theMode == OpenGl_GUM_PREPARE)
59 myRaytraceGeometry.ClearMaterials();
61 myArrayToTrianglesMap.clear();
63 myIsRaytraceDataValid = Standard_False;
66 // The set of processed structures (reflected to ray-tracing)
67 // This set is used to remove out-of-date records from the
68 // hash map of structures
69 std::set<const OpenGl_Structure*> anElements;
71 // Set to store all currently visible OpenGL primitive arrays
72 // applicable for ray-tracing
73 std::set<Standard_Size> anArrayIDs;
75 // Set to store all non-raytracable elements allowing tracking
76 // of changes in OpenGL scene (only for path tracing)
77 std::set<Standard_Integer> aNonRaytraceIDs;
79 const OpenGl_Layer& aLayer = myZLayers.Layer (Graphic3d_ZLayerId_Default);
81 if (aLayer.NbStructures() != 0)
83 const OpenGl_ArrayOfIndexedMapOfStructure& aStructArray = aLayer.ArrayOfStructures();
85 for (Standard_Integer anIndex = 0; anIndex < aStructArray.Length(); ++anIndex)
87 for (OpenGl_IndexedMapOfStructure::Iterator aStructIt (aStructArray (anIndex)); aStructIt.More(); aStructIt.Next())
89 const OpenGl_Structure* aStructure = aStructIt.Value();
91 if (theMode == OpenGl_GUM_CHECK)
93 if (toUpdateStructure (aStructure))
95 return updateRaytraceGeometry (OpenGl_GUM_PREPARE, theViewId, theGlContext);
97 else if (aStructure->IsVisible() && myRaytraceParameters.GlobalIllumination)
99 aNonRaytraceIDs.insert (aStructure->highlight ? aStructure->Id : -aStructure->Id);
102 else if (theMode == OpenGl_GUM_PREPARE)
104 if (!aStructure->IsRaytracable() || !aStructure->IsVisible())
108 else if (!aStructure->ViewAffinity.IsNull() && !aStructure->ViewAffinity->IsVisible (theViewId))
113 for (OpenGl_Structure::GroupIterator aGroupIter (aStructure->Groups()); aGroupIter.More(); aGroupIter.Next())
115 // Extract OpenGL elements from the group (primitives arrays)
116 for (const OpenGl_ElementNode* aNode = aGroupIter.Value()->FirstNode(); aNode != NULL; aNode = aNode->next)
118 OpenGl_PrimitiveArray* aPrimArray = dynamic_cast<OpenGl_PrimitiveArray*> (aNode->elem);
120 if (aPrimArray != NULL)
122 anArrayIDs.insert (aPrimArray->GetUID());
127 else if (theMode == OpenGl_GUM_REBUILD)
129 if (!aStructure->IsRaytracable())
133 else if (addRaytraceStructure (aStructure, theGlContext))
135 anElements.insert (aStructure); // structure was processed
142 if (theMode == OpenGl_GUM_PREPARE)
144 BVH_ObjectSet<Standard_ShortReal, 3>::BVH_ObjectList anUnchangedObjects;
146 // Filter out unchanged objects so only their transformations and materials
147 // will be updated (and newly added objects will be processed from scratch)
148 for (Standard_Integer anObjIdx = 0; anObjIdx < myRaytraceGeometry.Size(); ++anObjIdx)
150 OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
151 myRaytraceGeometry.Objects().ChangeValue (anObjIdx).operator->());
153 if (aTriangleSet == NULL)
158 if (anArrayIDs.find (aTriangleSet->AssociatedPArrayID()) != anArrayIDs.end())
160 anUnchangedObjects.Append (myRaytraceGeometry.Objects().Value (anObjIdx));
162 myArrayToTrianglesMap[aTriangleSet->AssociatedPArrayID()] = aTriangleSet;
166 myRaytraceGeometry.Objects() = anUnchangedObjects;
168 return updateRaytraceGeometry (OpenGl_GUM_REBUILD, theViewId, theGlContext);
170 else if (theMode == OpenGl_GUM_REBUILD)
172 // Actualize the hash map of structures - remove out-of-date records
173 std::map<const OpenGl_Structure*, StructState>::iterator anIter = myStructureStates.begin();
175 while (anIter != myStructureStates.end())
177 if (anElements.find (anIter->first) == anElements.end())
179 myStructureStates.erase (anIter++);
187 // Actualize OpenGL layer list state
188 myLayerListState = myZLayers.ModificationState();
190 // Rebuild two-level acceleration structure
191 myRaytraceGeometry.ProcessAcceleration();
193 myRaytraceSceneRadius = 2.f /* scale factor */ * std::max (
194 myRaytraceGeometry.Box().CornerMin().cwiseAbs().maxComp(),
195 myRaytraceGeometry.Box().CornerMax().cwiseAbs().maxComp());
197 const BVH_Vec3f aSize = myRaytraceGeometry.Box().Size();
199 myRaytraceSceneEpsilon = Max (1.0e-6f, 1.0e-4f * aSize.Modulus());
201 return uploadRaytraceData (theGlContext);
204 if (myRaytraceParameters.GlobalIllumination)
206 Standard_Boolean toRestart =
207 aNonRaytraceIDs.size() != myNonRaytraceStructureIDs.size();
209 for (std::set<Standard_Integer>::iterator anID = aNonRaytraceIDs.begin(); anID != aNonRaytraceIDs.end() && !toRestart; ++anID)
211 if (myNonRaytraceStructureIDs.find (*anID) == myNonRaytraceStructureIDs.end())
213 toRestart = Standard_True;
222 myNonRaytraceStructureIDs = aNonRaytraceIDs;
225 return Standard_True;
228 // =======================================================================
229 // function : toUpdateStructure
230 // purpose : Checks to see if the structure is modified
231 // =======================================================================
232 Standard_Boolean OpenGl_View::toUpdateStructure (const OpenGl_Structure* theStructure)
234 if (!theStructure->IsRaytracable())
236 if (theStructure->ModificationState() > 0)
238 theStructure->ResetModificationState();
240 return Standard_True; // ray-trace element was removed - need to rebuild
243 return Standard_False; // did not contain ray-trace elements
246 std::map<const OpenGl_Structure*, StructState>::iterator aStructState = myStructureStates.find (theStructure);
248 if (aStructState == myStructureStates.end() || aStructState->second.StructureState != theStructure->ModificationState())
250 return Standard_True;
252 else if (theStructure->InstancedStructure() != NULL)
254 return aStructState->second.InstancedState != theStructure->InstancedStructure()->ModificationState();
257 return Standard_False;
260 // =======================================================================
261 // function : buildTextureTransform
262 // purpose : Constructs texture transformation matrix
263 // =======================================================================
264 void buildTextureTransform (const Handle(Graphic3d_TextureParams)& theParams, BVH_Mat4f& theMatrix)
266 theMatrix.InitIdentity();
269 const Graphic3d_Vec2& aScale = theParams->Scale();
271 theMatrix.ChangeValue (0, 0) *= aScale.x();
272 theMatrix.ChangeValue (1, 0) *= aScale.x();
273 theMatrix.ChangeValue (2, 0) *= aScale.x();
274 theMatrix.ChangeValue (3, 0) *= aScale.x();
276 theMatrix.ChangeValue (0, 1) *= aScale.y();
277 theMatrix.ChangeValue (1, 1) *= aScale.y();
278 theMatrix.ChangeValue (2, 1) *= aScale.y();
279 theMatrix.ChangeValue (3, 1) *= aScale.y();
282 const Graphic3d_Vec2 aTrans = -theParams->Translation();
284 theMatrix.ChangeValue (0, 3) = theMatrix.GetValue (0, 0) * aTrans.x() +
285 theMatrix.GetValue (0, 1) * aTrans.y();
287 theMatrix.ChangeValue (1, 3) = theMatrix.GetValue (1, 0) * aTrans.x() +
288 theMatrix.GetValue (1, 1) * aTrans.y();
290 theMatrix.ChangeValue (2, 3) = theMatrix.GetValue (2, 0) * aTrans.x() +
291 theMatrix.GetValue (2, 1) * aTrans.y();
294 const Standard_ShortReal aSin = std::sin (
295 -theParams->Rotation() * static_cast<Standard_ShortReal> (M_PI / 180.0));
296 const Standard_ShortReal aCos = std::cos (
297 -theParams->Rotation() * static_cast<Standard_ShortReal> (M_PI / 180.0));
299 BVH_Mat4f aRotationMat;
300 aRotationMat.SetValue (0, 0, aCos);
301 aRotationMat.SetValue (1, 1, aCos);
302 aRotationMat.SetValue (0, 1, -aSin);
303 aRotationMat.SetValue (1, 0, aSin);
305 theMatrix = theMatrix * aRotationMat;
308 // =======================================================================
309 // function : convertMaterial
310 // purpose : Creates ray-tracing material properties
311 // =======================================================================
312 OpenGl_RaytraceMaterial OpenGl_View::convertMaterial (const OpenGl_AspectFace* theAspect,
313 const Handle(OpenGl_Context)& theGlContext)
315 OpenGl_RaytraceMaterial theMaterial;
317 const Graphic3d_MaterialAspect& aSrcMat = theAspect->Aspect()->FrontMaterial();
318 const OpenGl_Vec3& aMatCol = theAspect->Aspect()->InteriorColor();
319 const float aShine = 128.0f * float(aSrcMat.Shininess());
320 const bool isPhysic = aSrcMat.MaterialType (Graphic3d_MATERIAL_PHYSIC) == Standard_True;
323 if (aSrcMat.ReflectionMode (Graphic3d_TOR_AMBIENT))
325 const OpenGl_Vec3& aSrcAmb = isPhysic ? aSrcMat.AmbientColor() : aMatCol;
326 theMaterial.Ambient = BVH_Vec4f (aSrcAmb * (float )aSrcMat.Ambient(), 1.0f);
330 theMaterial.Ambient = THE_BLACK_COLOR;
333 // diffusion component
334 if (aSrcMat.ReflectionMode (Graphic3d_TOR_DIFFUSE))
336 const OpenGl_Vec3& aSrcDif = isPhysic ? aSrcMat.DiffuseColor() : aMatCol;
337 theMaterial.Diffuse = BVH_Vec4f (aSrcDif * (float )aSrcMat.Diffuse(), -1.0f); // -1 is no texture
341 theMaterial.Diffuse = BVH_Vec4f (THE_BLACK_COLOR.rgb(), -1.0f);
344 // specular component
345 if (aSrcMat.ReflectionMode (Graphic3d_TOR_SPECULAR))
347 const OpenGl_Vec3& aSrcSpe = aSrcMat.SpecularColor();
348 const OpenGl_Vec3& aSrcSpe2 = isPhysic ? aSrcSpe : THE_WHITE_COLOR.rgb();
349 theMaterial.Specular = BVH_Vec4f (aSrcSpe2 * (float )aSrcMat.Specular(), aShine);
351 const Standard_ShortReal aMaxRefl = Max (theMaterial.Diffuse.x() + theMaterial.Specular.x(),
352 Max (theMaterial.Diffuse.y() + theMaterial.Specular.y(),
353 theMaterial.Diffuse.z() + theMaterial.Specular.z()));
355 const Standard_ShortReal aReflectionScale = 0.75f / aMaxRefl;
357 // ignore isPhysic here
358 theMaterial.Reflection = BVH_Vec4f (aSrcSpe * (float )aSrcMat.Specular() * aReflectionScale, 0.0f);
362 theMaterial.Specular = BVH_Vec4f (THE_BLACK_COLOR.rgb(), aShine);
365 // emission component
366 if (aSrcMat.ReflectionMode (Graphic3d_TOR_EMISSION))
368 const OpenGl_Vec3& aSrcEms = isPhysic ? aSrcMat.EmissiveColor() : aMatCol;
369 theMaterial.Emission = BVH_Vec4f (aSrcEms * (float )aSrcMat.Emissive(), 1.0f);
373 theMaterial.Emission = THE_BLACK_COLOR;
376 const float anIndex = (float )aSrcMat.RefractionIndex();
377 theMaterial.Transparency = BVH_Vec4f (1.0f - (float )aSrcMat.Transparency(),
378 (float )aSrcMat.Transparency(),
379 anIndex == 0 ? 1.0f : anIndex,
380 anIndex == 0 ? 1.0f : 1.0f / anIndex);
382 // Serialize physically-based material properties
383 const Graphic3d_BSDF& aBSDF = aSrcMat.BSDF();
385 theMaterial.BSDF.Le = BVH_Vec4f (aBSDF.Le, 0.f);
386 theMaterial.BSDF.Kd = BVH_Vec4f (aBSDF.Kd, -1.f /* no tex */);
387 theMaterial.BSDF.Kr = BVH_Vec4f (aBSDF.Kr, 0.f);
388 theMaterial.BSDF.Kt = BVH_Vec4f (aBSDF.Kt, 0.f);
389 theMaterial.BSDF.Ks = BVH_Vec4f (aBSDF.Ks, aBSDF.Roughness);
391 theMaterial.BSDF.Fresnel = aBSDF.Fresnel.Serialize();
393 theMaterial.BSDF.Absorption = BVH_Vec4f (aBSDF.AbsorptionColor,
394 aBSDF.AbsorptionCoeff);
396 // Handle material textures
397 if (theAspect->Aspect()->ToMapTexture())
399 if (theGlContext->HasRayTracingTextures())
401 buildTextureTransform (theAspect->TextureParams(), theMaterial.TextureTransform);
403 // write texture ID to diffuse w-component
404 theMaterial.Diffuse.w() = theMaterial.BSDF.Kd.w() =
405 static_cast<Standard_ShortReal> (myRaytraceGeometry.AddTexture (theAspect->TextureRes (theGlContext)));
407 else if (!myIsRaytraceWarnTextures)
409 const TCollection_ExtendedString aWarnMessage =
410 "Warning: texturing in Ray-Trace requires GL_ARB_bindless_texture extension which is missing. "
411 "Please try to update graphics card driver. At the moment textures will be ignored.";
413 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
414 GL_DEBUG_TYPE_PORTABILITY, 0, GL_DEBUG_SEVERITY_HIGH, aWarnMessage);
416 myIsRaytraceWarnTextures = Standard_True;
423 // =======================================================================
424 // function : addRaytraceStructure
425 // purpose : Adds OpenGL structure to ray-traced scene geometry
426 // =======================================================================
427 Standard_Boolean OpenGl_View::addRaytraceStructure (const OpenGl_Structure* theStructure,
428 const Handle(OpenGl_Context)& theGlContext)
430 if (!theStructure->IsVisible())
432 myStructureStates[theStructure] = StructState (theStructure);
434 return Standard_True;
437 // Get structure material
438 OpenGl_RaytraceMaterial aDefaultMaterial;
439 Standard_Boolean aResult = addRaytraceGroups (theStructure, aDefaultMaterial, theStructure->Transformation(), theGlContext);
441 // Process all connected OpenGL structures
442 const OpenGl_Structure* anInstanced = theStructure->InstancedStructure();
444 if (anInstanced != NULL && anInstanced->IsRaytracable())
446 aResult &= addRaytraceGroups (anInstanced, aDefaultMaterial, theStructure->Transformation(), theGlContext);
449 myStructureStates[theStructure] = StructState (theStructure);
454 // =======================================================================
455 // function : addRaytraceGroups
456 // purpose : Adds OpenGL groups to ray-traced scene geometry
457 // =======================================================================
458 Standard_Boolean OpenGl_View::addRaytraceGroups (const OpenGl_Structure* theStructure,
459 const OpenGl_RaytraceMaterial& theStructMat,
460 const Handle(Geom_Transformation)& theTrsf,
461 const Handle(OpenGl_Context)& theGlContext)
464 for (OpenGl_Structure::GroupIterator aGroupIter (theStructure->Groups()); aGroupIter.More(); aGroupIter.Next())
466 // Get group material
467 OpenGl_RaytraceMaterial aGroupMaterial;
468 if (aGroupIter.Value()->AspectFace() != NULL)
470 aGroupMaterial = convertMaterial (
471 aGroupIter.Value()->AspectFace(), theGlContext);
474 Standard_Integer aMatID = static_cast<Standard_Integer> (myRaytraceGeometry.Materials.size());
476 // Use group material if available, otherwise use structure material
477 myRaytraceGeometry.Materials.push_back (
478 aGroupIter.Value()->AspectFace() != NULL ? aGroupMaterial : theStructMat);
480 // Add OpenGL elements from group (extract primitives arrays and aspects)
481 for (const OpenGl_ElementNode* aNode = aGroupIter.Value()->FirstNode(); aNode != NULL; aNode = aNode->next)
483 OpenGl_AspectFace* anAspect = dynamic_cast<OpenGl_AspectFace*> (aNode->elem);
485 if (anAspect != NULL)
487 aMatID = static_cast<Standard_Integer> (myRaytraceGeometry.Materials.size());
489 OpenGl_RaytraceMaterial aMaterial = convertMaterial (anAspect, theGlContext);
491 myRaytraceGeometry.Materials.push_back (aMaterial);
495 OpenGl_PrimitiveArray* aPrimArray = dynamic_cast<OpenGl_PrimitiveArray*> (aNode->elem);
497 if (aPrimArray != NULL)
499 std::map<Standard_Size, OpenGl_TriangleSet*>::iterator aSetIter = myArrayToTrianglesMap.find (aPrimArray->GetUID());
501 if (aSetIter != myArrayToTrianglesMap.end())
503 OpenGl_TriangleSet* aSet = aSetIter->second;
505 BVH_Transform<Standard_ShortReal, 4>* aTransform = new BVH_Transform<Standard_ShortReal, 4>();
507 if (!theTrsf.IsNull())
509 theTrsf->Trsf().GetMat4 (aMat4);
510 aTransform->SetTransform (aMat4);
513 aSet->SetProperties (aTransform);
515 if (aSet->MaterialIndex() != OpenGl_TriangleSet::INVALID_MATERIAL && aSet->MaterialIndex() != aMatID)
517 aSet->SetMaterialIndex (aMatID);
522 NCollection_Handle<BVH_Object<Standard_ShortReal, 3> > aSet =
523 addRaytracePrimitiveArray (aPrimArray, aMatID, 0);
527 BVH_Transform<Standard_ShortReal, 4>* aTransform = new BVH_Transform<Standard_ShortReal, 4>;
529 if (!theTrsf.IsNull())
531 theTrsf->Trsf().GetMat4 (aMat4);
532 aTransform->SetTransform (aMat4);
535 aSet->SetProperties (aTransform);
537 myRaytraceGeometry.Objects().Append (aSet);
545 return Standard_True;
548 // =======================================================================
549 // function : addRaytracePrimitiveArray
550 // purpose : Adds OpenGL primitive array to ray-traced scene geometry
551 // =======================================================================
552 OpenGl_TriangleSet* OpenGl_View::addRaytracePrimitiveArray (const OpenGl_PrimitiveArray* theArray,
553 const Standard_Integer theMaterial,
554 const OpenGl_Mat4* theTransform)
556 const Handle(Graphic3d_BoundBuffer)& aBounds = theArray->Bounds();
557 const Handle(Graphic3d_IndexBuffer)& anIndices = theArray->Indices();
558 const Handle(Graphic3d_Buffer)& anAttribs = theArray->Attributes();
560 if (theArray->DrawMode() < GL_TRIANGLES
561 #ifndef GL_ES_VERSION_2_0
562 || theArray->DrawMode() > GL_POLYGON
564 || theArray->DrawMode() > GL_TRIANGLE_FAN
566 || anAttribs.IsNull())
571 OpenGl_Mat4 aNormalMatrix;
573 if (theTransform != NULL)
575 Standard_ASSERT_RETURN (theTransform->Inverted (aNormalMatrix),
576 "Error: Failed to compute normal transformation matrix", NULL);
578 aNormalMatrix.Transpose();
581 OpenGl_TriangleSet* aSet = new OpenGl_TriangleSet (theArray->GetUID());
583 aSet->Vertices.reserve (anAttribs->NbElements);
584 aSet->Normals.reserve (anAttribs->NbElements);
585 aSet->TexCrds.reserve (anAttribs->NbElements);
587 const size_t aVertFrom = aSet->Vertices.size();
589 for (Standard_Integer anAttribIter = 0; anAttribIter < anAttribs->NbAttributes; ++anAttribIter)
591 const Graphic3d_Attribute& anAttrib = anAttribs->Attribute (anAttribIter);
592 const size_t anOffset = anAttribs->AttributeOffset (anAttribIter);
593 if (anAttrib.Id == Graphic3d_TOA_POS)
595 if (anAttrib.DataType == Graphic3d_TOD_VEC3
596 || anAttrib.DataType == Graphic3d_TOD_VEC4)
598 for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
600 aSet->Vertices.push_back (
601 *reinterpret_cast<const Graphic3d_Vec3*> (anAttribs->value (aVertIter) + anOffset));
604 else if (anAttrib.DataType == Graphic3d_TOD_VEC2)
606 for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
608 const Standard_ShortReal* aCoords =
609 reinterpret_cast<const Standard_ShortReal*> (anAttribs->value (aVertIter) + anOffset);
611 aSet->Vertices.push_back (BVH_Vec3f (aCoords[0], aCoords[1], 0.0f));
615 else if (anAttrib.Id == Graphic3d_TOA_NORM)
617 if (anAttrib.DataType == Graphic3d_TOD_VEC3
618 || anAttrib.DataType == Graphic3d_TOD_VEC4)
620 for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
622 aSet->Normals.push_back (
623 *reinterpret_cast<const Graphic3d_Vec3*> (anAttribs->value (aVertIter) + anOffset));
627 else if (anAttrib.Id == Graphic3d_TOA_UV)
629 if (anAttrib.DataType == Graphic3d_TOD_VEC2)
631 for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
633 aSet->TexCrds.push_back (
634 *reinterpret_cast<const Graphic3d_Vec2*> (anAttribs->value (aVertIter) + anOffset));
640 if (aSet->Normals.size() != aSet->Vertices.size())
642 for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
644 aSet->Normals.push_back (BVH_Vec3f());
648 if (aSet->TexCrds.size() != aSet->Vertices.size())
650 for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
652 aSet->TexCrds.push_back (BVH_Vec2f());
656 if (theTransform != NULL)
658 for (size_t aVertIter = aVertFrom; aVertIter < aSet->Vertices.size(); ++aVertIter)
660 BVH_Vec3f& aVertex = aSet->Vertices[aVertIter];
662 BVH_Vec4f aTransVertex = *theTransform *
663 BVH_Vec4f (aVertex.x(), aVertex.y(), aVertex.z(), 1.f);
665 aVertex = BVH_Vec3f (aTransVertex.x(), aTransVertex.y(), aTransVertex.z());
667 for (size_t aVertIter = aVertFrom; aVertIter < aSet->Normals.size(); ++aVertIter)
669 BVH_Vec3f& aNormal = aSet->Normals[aVertIter];
671 BVH_Vec4f aTransNormal = aNormalMatrix *
672 BVH_Vec4f (aNormal.x(), aNormal.y(), aNormal.z(), 0.f);
674 aNormal = BVH_Vec3f (aTransNormal.x(), aTransNormal.y(), aTransNormal.z());
678 if (!aBounds.IsNull())
680 for (Standard_Integer aBound = 0, aBoundStart = 0; aBound < aBounds->NbBounds; ++aBound)
682 const Standard_Integer aVertNum = aBounds->Bounds[aBound];
684 if (!addRaytraceVertexIndices (*aSet, theMaterial, aVertNum, aBoundStart, *theArray))
690 aBoundStart += aVertNum;
695 const Standard_Integer aVertNum = !anIndices.IsNull() ? anIndices->NbElements : anAttribs->NbElements;
697 if (!addRaytraceVertexIndices (*aSet, theMaterial, aVertNum, 0, *theArray))
705 if (aSet->Size() != 0)
713 // =======================================================================
714 // function : addRaytraceVertexIndices
715 // purpose : Adds vertex indices to ray-traced scene geometry
716 // =======================================================================
717 Standard_Boolean OpenGl_View::addRaytraceVertexIndices (OpenGl_TriangleSet& theSet,
718 const Standard_Integer theMatID,
719 const Standard_Integer theCount,
720 const Standard_Integer theOffset,
721 const OpenGl_PrimitiveArray& theArray)
723 switch (theArray.DrawMode())
725 case GL_TRIANGLES: return addRaytraceTriangleArray (theSet, theMatID, theCount, theOffset, theArray.Indices());
726 case GL_TRIANGLE_FAN: return addRaytraceTriangleFanArray (theSet, theMatID, theCount, theOffset, theArray.Indices());
727 case GL_TRIANGLE_STRIP: return addRaytraceTriangleStripArray (theSet, theMatID, theCount, theOffset, theArray.Indices());
728 #if !defined(GL_ES_VERSION_2_0)
729 case GL_QUAD_STRIP: return addRaytraceQuadrangleStripArray (theSet, theMatID, theCount, theOffset, theArray.Indices());
730 case GL_QUADS: return addRaytraceQuadrangleArray (theSet, theMatID, theCount, theOffset, theArray.Indices());
731 case GL_POLYGON: return addRaytracePolygonArray (theSet, theMatID, theCount, theOffset, theArray.Indices());
735 return Standard_False;
738 // =======================================================================
739 // function : addRaytraceTriangleArray
740 // purpose : Adds OpenGL triangle array to ray-traced scene geometry
741 // =======================================================================
742 Standard_Boolean OpenGl_View::addRaytraceTriangleArray (OpenGl_TriangleSet& theSet,
743 const Standard_Integer theMatID,
744 const Standard_Integer theCount,
745 const Standard_Integer theOffset,
746 const Handle(Graphic3d_IndexBuffer)& theIndices)
750 return Standard_True;
753 theSet.Elements.reserve (theSet.Elements.size() + theCount / 3);
755 if (!theIndices.IsNull())
757 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; aVert += 3)
759 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0),
760 theIndices->Index (aVert + 1),
761 theIndices->Index (aVert + 2),
767 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; aVert += 3)
769 theSet.Elements.push_back (BVH_Vec4i (aVert + 0, aVert + 1, aVert + 2, theMatID));
773 return Standard_True;
776 // =======================================================================
777 // function : addRaytraceTriangleFanArray
778 // purpose : Adds OpenGL triangle fan array to ray-traced scene geometry
779 // =======================================================================
780 Standard_Boolean OpenGl_View::addRaytraceTriangleFanArray (OpenGl_TriangleSet& theSet,
781 const Standard_Integer theMatID,
782 const Standard_Integer theCount,
783 const Standard_Integer theOffset,
784 const Handle(Graphic3d_IndexBuffer)& theIndices)
788 return Standard_True;
791 theSet.Elements.reserve (theSet.Elements.size() + theCount - 2);
793 if (!theIndices.IsNull())
795 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
797 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (theOffset),
798 theIndices->Index (aVert + 1),
799 theIndices->Index (aVert + 2),
805 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
807 theSet.Elements.push_back (BVH_Vec4i (theOffset,
814 return Standard_True;
817 // =======================================================================
818 // function : addRaytraceTriangleStripArray
819 // purpose : Adds OpenGL triangle strip array to ray-traced scene geometry
820 // =======================================================================
821 Standard_Boolean OpenGl_View::addRaytraceTriangleStripArray (OpenGl_TriangleSet& theSet,
822 const Standard_Integer theMatID,
823 const Standard_Integer theCount,
824 const Standard_Integer theOffset,
825 const Handle(Graphic3d_IndexBuffer)& theIndices)
829 return Standard_True;
832 theSet.Elements.reserve (theSet.Elements.size() + theCount - 2);
834 if (!theIndices.IsNull())
836 for (Standard_Integer aVert = theOffset, aCW = 0; aVert < theOffset + theCount - 2; ++aVert, aCW = (aCW + 1) % 2)
838 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + (aCW ? 1 : 0)),
839 theIndices->Index (aVert + (aCW ? 0 : 1)),
840 theIndices->Index (aVert + 2),
846 for (Standard_Integer aVert = theOffset, aCW = 0; aVert < theOffset + theCount - 2; ++aVert, aCW = (aCW + 1) % 2)
848 theSet.Elements.push_back (BVH_Vec4i (aVert + (aCW ? 1 : 0),
849 aVert + (aCW ? 0 : 1),
855 return Standard_True;
858 // =======================================================================
859 // function : addRaytraceQuadrangleArray
860 // purpose : Adds OpenGL quad array to ray-traced scene geometry
861 // =======================================================================
862 Standard_Boolean OpenGl_View::addRaytraceQuadrangleArray (OpenGl_TriangleSet& theSet,
863 const Standard_Integer theMatID,
864 const Standard_Integer theCount,
865 const Standard_Integer theOffset,
866 const Handle(Graphic3d_IndexBuffer)& theIndices)
870 return Standard_True;
873 theSet.Elements.reserve (theSet.Elements.size() + theCount / 2);
875 if (!theIndices.IsNull())
877 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 4)
879 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0),
880 theIndices->Index (aVert + 1),
881 theIndices->Index (aVert + 2),
883 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0),
884 theIndices->Index (aVert + 2),
885 theIndices->Index (aVert + 3),
891 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 4)
893 theSet.Elements.push_back (BVH_Vec4i (aVert + 0, aVert + 1, aVert + 2,
895 theSet.Elements.push_back (BVH_Vec4i (aVert + 0, aVert + 2, aVert + 3,
900 return Standard_True;
903 // =======================================================================
904 // function : addRaytraceQuadrangleStripArray
905 // purpose : Adds OpenGL quad strip array to ray-traced scene geometry
906 // =======================================================================
907 Standard_Boolean OpenGl_View::addRaytraceQuadrangleStripArray (OpenGl_TriangleSet& theSet,
908 const Standard_Integer theMatID,
909 const Standard_Integer theCount,
910 const Standard_Integer theOffset,
911 const Handle(Graphic3d_IndexBuffer)& theIndices)
915 return Standard_True;
918 theSet.Elements.reserve (theSet.Elements.size() + 2 * theCount - 6);
920 if (!theIndices.IsNull())
922 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 2)
924 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0),
925 theIndices->Index (aVert + 1),
926 theIndices->Index (aVert + 2),
929 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 1),
930 theIndices->Index (aVert + 3),
931 theIndices->Index (aVert + 2),
937 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 2)
939 theSet.Elements.push_back (BVH_Vec4i (aVert + 0,
944 theSet.Elements.push_back (BVH_Vec4i (aVert + 1,
951 return Standard_True;
954 // =======================================================================
955 // function : addRaytracePolygonArray
956 // purpose : Adds OpenGL polygon array to ray-traced scene geometry
957 // =======================================================================
958 Standard_Boolean OpenGl_View::addRaytracePolygonArray (OpenGl_TriangleSet& theSet,
959 const Standard_Integer theMatID,
960 const Standard_Integer theCount,
961 const Standard_Integer theOffset,
962 const Handle(Graphic3d_IndexBuffer)& theIndices)
966 return Standard_True;
969 theSet.Elements.reserve (theSet.Elements.size() + theCount - 2);
971 if (!theIndices.IsNull())
973 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
975 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (theOffset),
976 theIndices->Index (aVert + 1),
977 theIndices->Index (aVert + 2),
983 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
985 theSet.Elements.push_back (BVH_Vec4i (theOffset,
992 return Standard_True;
995 const TCollection_AsciiString OpenGl_View::ShaderSource::EMPTY_PREFIX;
997 // =======================================================================
999 // purpose : Returns shader source combined with prefix
1000 // =======================================================================
1001 TCollection_AsciiString OpenGl_View::ShaderSource::Source() const
1003 const TCollection_AsciiString aVersion = "#version 140";
1005 if (myPrefix.IsEmpty())
1007 return aVersion + "\n" + mySource;
1010 return aVersion + "\n" + myPrefix + "\n" + mySource;
1013 // =======================================================================
1015 // purpose : Loads shader source from specified files
1016 // =======================================================================
1017 Standard_Boolean OpenGl_View::ShaderSource::Load (const TCollection_AsciiString* theFileNames,
1018 const TCollection_AsciiString& thePrefix)
1022 TCollection_AsciiString aMissingFiles;
1023 for (Standard_Integer anIndex = 0; !theFileNames[anIndex].IsEmpty(); ++anIndex)
1025 OSD_File aFile (theFileNames[anIndex]);
1028 aFile.Open (OSD_ReadOnly, OSD_Protection());
1030 if (!aFile.IsOpen())
1032 if (!aMissingFiles.IsEmpty())
1034 aMissingFiles += ", ";
1036 aMissingFiles += TCollection_AsciiString("'") + theFileNames[anIndex] + "'";
1039 else if (!aMissingFiles.IsEmpty())
1045 TCollection_AsciiString aSource;
1046 aFile.Read (aSource, (Standard_Integer) aFile.Size());
1047 if (!aSource.IsEmpty())
1049 mySource += TCollection_AsciiString ("\n") + aSource;
1054 myPrefix = thePrefix;
1055 if (!aMissingFiles.IsEmpty())
1057 myError = TCollection_AsciiString("Shader files ") + aMissingFiles + " are missing or inaccessible";
1058 return Standard_False;
1060 return Standard_True;
1063 // =======================================================================
1064 // function : generateShaderPrefix
1065 // purpose : Generates shader prefix based on current ray-tracing options
1066 // =======================================================================
1067 TCollection_AsciiString OpenGl_View::generateShaderPrefix (const Handle(OpenGl_Context)& theGlContext) const
1069 TCollection_AsciiString aPrefixString =
1070 TCollection_AsciiString ("#define STACK_SIZE ") + TCollection_AsciiString (myRaytraceParameters.StackSize) + "\n" +
1071 TCollection_AsciiString ("#define NB_BOUNCES ") + TCollection_AsciiString (myRaytraceParameters.NbBounces);
1073 if (myRaytraceParameters.TransparentShadows)
1075 aPrefixString += TCollection_AsciiString ("\n#define TRANSPARENT_SHADOWS");
1078 // If OpenGL driver supports bindless textures and texturing
1079 // is actually used, activate texturing in ray-tracing mode
1080 if (myRaytraceParameters.UseBindlessTextures && theGlContext->arbTexBindless != NULL)
1082 aPrefixString += TCollection_AsciiString ("\n#define USE_TEXTURES") +
1083 TCollection_AsciiString ("\n#define MAX_TEX_NUMBER ") + TCollection_AsciiString (OpenGl_RaytraceGeometry::MAX_TEX_NUMBER);
1086 if (myRaytraceParameters.GlobalIllumination) // path tracing activated
1088 aPrefixString += TCollection_AsciiString ("\n#define PATH_TRACING");
1090 if (myRaytraceParameters.AdaptiveScreenSampling) // adaptive screen sampling requested
1092 // to activate the feature we need OpenGL 4.4 and GL_NV_shader_atomic_float extension
1093 if (theGlContext->IsGlGreaterEqual (4, 4) && theGlContext->CheckExtension ("GL_NV_shader_atomic_float"))
1095 aPrefixString += TCollection_AsciiString ("\n#define ADAPTIVE_SAMPLING") +
1096 TCollection_AsciiString ("\n#define BLOCK_SIZE ") + TCollection_AsciiString (OpenGl_TileSampler::TileSize());
1101 return aPrefixString;
1104 // =======================================================================
1105 // function : safeFailBack
1106 // purpose : Performs safe exit when shaders initialization fails
1107 // =======================================================================
1108 Standard_Boolean OpenGl_View::safeFailBack (const TCollection_ExtendedString& theMessage,
1109 const Handle(OpenGl_Context)& theGlContext)
1111 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1112 GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, theMessage);
1114 myRaytraceInitStatus = OpenGl_RT_FAIL;
1116 releaseRaytraceResources (theGlContext);
1118 return Standard_False;
1121 // =======================================================================
1122 // function : initShader
1123 // purpose : Creates new shader object with specified source
1124 // =======================================================================
1125 Handle(OpenGl_ShaderObject) OpenGl_View::initShader (const GLenum theType,
1126 const ShaderSource& theSource,
1127 const Handle(OpenGl_Context)& theGlContext)
1129 Handle(OpenGl_ShaderObject) aShader = new OpenGl_ShaderObject (theType);
1131 if (!aShader->Create (theGlContext))
1133 const TCollection_ExtendedString aMessage = TCollection_ExtendedString ("Error: Failed to create ") +
1134 (theType == GL_VERTEX_SHADER ? "vertex" : "fragment") + " shader object";
1136 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1137 GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, aMessage);
1139 aShader->Release (theGlContext.operator->());
1141 return Handle(OpenGl_ShaderObject)();
1144 if (!aShader->LoadSource (theGlContext, theSource.Source()))
1146 const TCollection_ExtendedString aMessage = TCollection_ExtendedString ("Error: Failed to set ") +
1147 (theType == GL_VERTEX_SHADER ? "vertex" : "fragment") + " shader source";
1149 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1150 GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, aMessage);
1152 aShader->Release (theGlContext.operator->());
1154 return Handle(OpenGl_ShaderObject)();
1157 TCollection_AsciiString aBuildLog;
1159 if (!aShader->Compile (theGlContext))
1161 aShader->FetchInfoLog (theGlContext, aBuildLog);
1163 const TCollection_ExtendedString aMessage = TCollection_ExtendedString ("Error: Failed to compile ") +
1164 (theType == GL_VERTEX_SHADER ? "vertex" : "fragment") + " shader object:\n" + aBuildLog;
1166 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1167 GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, aMessage);
1169 aShader->Release (theGlContext.operator->());
1171 #ifdef RAY_TRACE_PRINT_INFO
1172 std::cout << "Shader build log:\n" << aBuildLog << "\n";
1175 return Handle(OpenGl_ShaderObject)();
1177 else if (theGlContext->caps->glslWarnings)
1179 aShader->FetchInfoLog (theGlContext, aBuildLog);
1181 if (!aBuildLog.IsEmpty() && !aBuildLog.IsEqual ("No errors.\n"))
1183 const TCollection_ExtendedString aMessage = TCollection_ExtendedString (theType == GL_VERTEX_SHADER ?
1184 "Vertex" : "Fragment") + " shader was compiled with following warnings:\n" + aBuildLog;
1186 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1187 GL_DEBUG_TYPE_PORTABILITY, 0, GL_DEBUG_SEVERITY_LOW, aMessage);
1190 #ifdef RAY_TRACE_PRINT_INFO
1191 std::cout << "Shader build log:\n" << aBuildLog << "\n";
1198 // =======================================================================
1199 // function : initProgram
1200 // purpose : Creates GLSL program from the given shader objects
1201 // =======================================================================
1202 Handle(OpenGl_ShaderProgram) OpenGl_View::initProgram (const Handle(OpenGl_Context)& theGlContext,
1203 const Handle(OpenGl_ShaderObject)& theVertShader,
1204 const Handle(OpenGl_ShaderObject)& theFragShader)
1206 Handle(OpenGl_ShaderProgram) aProgram = new OpenGl_ShaderProgram;
1208 if (!aProgram->Create (theGlContext))
1210 theVertShader->Release (theGlContext.operator->());
1212 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1213 GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, "Failed to create shader program");
1215 return Handle(OpenGl_ShaderProgram)();
1218 if (!aProgram->AttachShader (theGlContext, theVertShader)
1219 || !aProgram->AttachShader (theGlContext, theFragShader))
1221 theVertShader->Release (theGlContext.operator->());
1223 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1224 GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, "Failed to attach shader objects");
1226 return Handle(OpenGl_ShaderProgram)();
1229 aProgram->SetAttributeName (theGlContext, Graphic3d_TOA_POS, "occVertex");
1231 TCollection_AsciiString aLinkLog;
1233 if (!aProgram->Link (theGlContext))
1235 aProgram->FetchInfoLog (theGlContext, aLinkLog);
1237 const TCollection_ExtendedString aMessage = TCollection_ExtendedString (
1238 "Failed to link shader program:\n") + aLinkLog;
1240 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1241 GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, aMessage);
1243 return Handle(OpenGl_ShaderProgram)();
1245 else if (theGlContext->caps->glslWarnings)
1247 aProgram->FetchInfoLog (theGlContext, aLinkLog);
1248 if (!aLinkLog.IsEmpty() && !aLinkLog.IsEqual ("No errors.\n"))
1250 const TCollection_ExtendedString aMessage = TCollection_ExtendedString (
1251 "Shader program was linked with following warnings:\n") + aLinkLog;
1253 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1254 GL_DEBUG_TYPE_PORTABILITY, 0, GL_DEBUG_SEVERITY_LOW, aMessage);
1261 // =======================================================================
1262 // function : initRaytraceResources
1263 // purpose : Initializes OpenGL/GLSL shader programs
1264 // =======================================================================
1265 Standard_Boolean OpenGl_View::initRaytraceResources (const Handle(OpenGl_Context)& theGlContext)
1267 if (myRaytraceInitStatus == OpenGl_RT_FAIL)
1269 return Standard_False;
1272 Standard_Boolean aToRebuildShaders = Standard_False;
1274 if (myRenderParams.RebuildRayTracingShaders) // requires complete re-initialization
1276 myRaytraceInitStatus = OpenGl_RT_NONE;
1277 releaseRaytraceResources (theGlContext, Standard_True);
1278 myRenderParams.RebuildRayTracingShaders = Standard_False; // clear rebuilding flag
1281 if (myRaytraceInitStatus == OpenGl_RT_INIT)
1283 if (!myIsRaytraceDataValid)
1285 return Standard_True;
1288 const Standard_Integer aRequiredStackSize =
1289 myRaytraceGeometry.TopLevelTreeDepth() + myRaytraceGeometry.BotLevelTreeDepth();
1291 if (myRaytraceParameters.StackSize < aRequiredStackSize)
1293 myRaytraceParameters.StackSize = Max (aRequiredStackSize, THE_DEFAULT_STACK_SIZE);
1295 aToRebuildShaders = Standard_True;
1299 if (aRequiredStackSize < myRaytraceParameters.StackSize)
1301 if (myRaytraceParameters.StackSize > THE_DEFAULT_STACK_SIZE)
1303 myRaytraceParameters.StackSize = Max (aRequiredStackSize, THE_DEFAULT_STACK_SIZE);
1304 aToRebuildShaders = Standard_True;
1309 if (myRenderParams.RaytracingDepth != myRaytraceParameters.NbBounces)
1311 myRaytraceParameters.NbBounces = myRenderParams.RaytracingDepth;
1312 aToRebuildShaders = Standard_True;
1315 if (myRaytraceGeometry.HasTextures() != myRaytraceParameters.UseBindlessTextures)
1317 myRaytraceParameters.UseBindlessTextures = myRaytraceGeometry.HasTextures();
1318 aToRebuildShaders = Standard_True;
1321 if (myRenderParams.IsTransparentShadowEnabled != myRaytraceParameters.TransparentShadows)
1323 myRaytraceParameters.TransparentShadows = myRenderParams.IsTransparentShadowEnabled;
1324 aToRebuildShaders = Standard_True;
1327 if (myRenderParams.IsGlobalIlluminationEnabled != myRaytraceParameters.GlobalIllumination)
1329 myRaytraceParameters.GlobalIllumination = myRenderParams.IsGlobalIlluminationEnabled;
1330 aToRebuildShaders = Standard_True;
1333 if (myRenderParams.AdaptiveScreenSampling != myRaytraceParameters.AdaptiveScreenSampling)
1335 myRaytraceParameters.AdaptiveScreenSampling = myRenderParams.AdaptiveScreenSampling;
1336 if (myRenderParams.AdaptiveScreenSampling) // adaptive sampling was requested
1338 if (!theGlContext->HasRayTracingAdaptiveSampling())
1340 // disable the feature if it is not supported
1341 myRaytraceParameters.AdaptiveScreenSampling = myRenderParams.AdaptiveScreenSampling = Standard_False;
1342 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_PORTABILITY, 0, GL_DEBUG_SEVERITY_LOW,
1343 "Adaptive sampling not supported (OpenGL 4.4 or GL_NV_shader_atomic_float is missing)");
1347 aToRebuildShaders = Standard_True;
1350 if (aToRebuildShaders)
1352 // Reject accumulated frames
1355 // Environment map should be updated
1356 myToUpdateEnvironmentMap = Standard_True;
1358 const TCollection_AsciiString aPrefixString = generateShaderPrefix (theGlContext);
1360 #ifdef RAY_TRACE_PRINT_INFO
1361 std::cout << "GLSL prefix string:" << std::endl << aPrefixString << std::endl;
1364 myRaytraceShaderSource.SetPrefix (aPrefixString);
1365 myPostFSAAShaderSource.SetPrefix (aPrefixString);
1366 myOutImageShaderSource.SetPrefix (aPrefixString);
1368 if (!myRaytraceShader->LoadSource (theGlContext, myRaytraceShaderSource.Source())
1369 || !myPostFSAAShader->LoadSource (theGlContext, myPostFSAAShaderSource.Source())
1370 || !myOutImageShader->LoadSource (theGlContext, myOutImageShaderSource.Source()))
1372 return safeFailBack ("Failed to load source into ray-tracing fragment shaders", theGlContext);
1375 if (!myRaytraceShader->Compile (theGlContext)
1376 || !myPostFSAAShader->Compile (theGlContext)
1377 || !myOutImageShader->Compile (theGlContext))
1379 return safeFailBack ("Failed to compile ray-tracing fragment shaders", theGlContext);
1382 myRaytraceProgram->SetAttributeName (theGlContext, Graphic3d_TOA_POS, "occVertex");
1383 myPostFSAAProgram->SetAttributeName (theGlContext, Graphic3d_TOA_POS, "occVertex");
1384 myOutImageProgram->SetAttributeName (theGlContext, Graphic3d_TOA_POS, "occVertex");
1386 if (!myRaytraceProgram->Link (theGlContext)
1387 || !myPostFSAAProgram->Link (theGlContext)
1388 || !myOutImageProgram->Link (theGlContext))
1390 return safeFailBack ("Failed to initialize vertex attributes for ray-tracing program", theGlContext);
1395 if (myRaytraceInitStatus == OpenGl_RT_NONE)
1397 myAccumFrames = 0; // reject accumulated frames
1399 if (!theGlContext->IsGlGreaterEqual (3, 1))
1401 return safeFailBack ("Ray-tracing requires OpenGL 3.1 and higher", theGlContext);
1403 else if (!theGlContext->arbTboRGB32)
1405 return safeFailBack ("Ray-tracing requires OpenGL 4.0+ or GL_ARB_texture_buffer_object_rgb32 extension", theGlContext);
1407 else if (!theGlContext->arbFBOBlit)
1409 return safeFailBack ("Ray-tracing requires EXT_framebuffer_blit extension", theGlContext);
1412 myRaytraceParameters.NbBounces = myRenderParams.RaytracingDepth;
1414 const TCollection_AsciiString aFolder = Graphic3d_ShaderProgram::ShadersFolder();
1416 if (aFolder.IsEmpty())
1418 return safeFailBack ("Failed to locate shaders directory", theGlContext);
1421 if (myIsRaytraceDataValid)
1423 myRaytraceParameters.StackSize = Max (THE_DEFAULT_STACK_SIZE,
1424 myRaytraceGeometry.TopLevelTreeDepth() + myRaytraceGeometry.BotLevelTreeDepth());
1427 const TCollection_AsciiString aPrefixString = generateShaderPrefix (theGlContext);
1429 #ifdef RAY_TRACE_PRINT_INFO
1430 std::cout << "GLSL prefix string:" << std::endl << aPrefixString << std::endl;
1433 ShaderSource aBasicVertShaderSrc;
1435 TCollection_AsciiString aFiles[] = { aFolder + "/RaytraceBase.vs", "" };
1436 if (!aBasicVertShaderSrc.Load (aFiles))
1438 return safeFailBack (aBasicVertShaderSrc.ErrorDescription(), theGlContext);
1443 TCollection_AsciiString aFiles[] = { aFolder + "/RaytraceBase.fs",
1444 aFolder + "/PathtraceBase.fs",
1445 aFolder + "/RaytraceRender.fs",
1447 if (!myRaytraceShaderSource.Load (aFiles, aPrefixString))
1449 return safeFailBack (myRaytraceShaderSource.ErrorDescription(), theGlContext);
1452 Handle(OpenGl_ShaderObject) aBasicVertShader = initShader (GL_VERTEX_SHADER, aBasicVertShaderSrc, theGlContext);
1453 if (aBasicVertShader.IsNull())
1455 return safeFailBack ("Failed to initialize ray-trace vertex shader", theGlContext);
1458 myRaytraceShader = initShader (GL_FRAGMENT_SHADER, myRaytraceShaderSource, theGlContext);
1459 if (myRaytraceShader.IsNull())
1461 aBasicVertShader->Release (theGlContext.operator->());
1462 return safeFailBack ("Failed to initialize ray-trace fragment shader", theGlContext);
1465 myRaytraceProgram = initProgram (theGlContext, aBasicVertShader, myRaytraceShader);
1466 if (myRaytraceProgram.IsNull())
1468 return safeFailBack ("Failed to initialize ray-trace shader program", theGlContext);
1473 TCollection_AsciiString aFiles[] = { aFolder + "/RaytraceBase.fs",
1474 aFolder + "/RaytraceSmooth.fs",
1476 if (!myPostFSAAShaderSource.Load (aFiles, aPrefixString))
1478 return safeFailBack (myPostFSAAShaderSource.ErrorDescription(), theGlContext);
1481 Handle(OpenGl_ShaderObject) aBasicVertShader = initShader (GL_VERTEX_SHADER, aBasicVertShaderSrc, theGlContext);
1482 if (aBasicVertShader.IsNull())
1484 return safeFailBack ("Failed to initialize FSAA vertex shader", theGlContext);
1487 myPostFSAAShader = initShader (GL_FRAGMENT_SHADER, myPostFSAAShaderSource, theGlContext);
1488 if (myPostFSAAShader.IsNull())
1490 aBasicVertShader->Release (theGlContext.operator->());
1491 return safeFailBack ("Failed to initialize FSAA fragment shader", theGlContext);
1494 myPostFSAAProgram = initProgram (theGlContext, aBasicVertShader, myPostFSAAShader);
1495 if (myPostFSAAProgram.IsNull())
1497 return safeFailBack ("Failed to initialize FSAA shader program", theGlContext);
1502 TCollection_AsciiString aFiles[] = { aFolder + "/Display.fs", "" };
1503 if (!myOutImageShaderSource.Load (aFiles, aPrefixString))
1505 return safeFailBack (myOutImageShaderSource.ErrorDescription(), theGlContext);
1508 Handle(OpenGl_ShaderObject) aBasicVertShader = initShader (GL_VERTEX_SHADER, aBasicVertShaderSrc, theGlContext);
1509 if (aBasicVertShader.IsNull())
1511 return safeFailBack ("Failed to set vertex shader source", theGlContext);
1514 myOutImageShader = initShader (GL_FRAGMENT_SHADER, myOutImageShaderSource, theGlContext);
1515 if (myOutImageShader.IsNull())
1517 aBasicVertShader->Release (theGlContext.operator->());
1518 return safeFailBack ("Failed to set display fragment shader source", theGlContext);
1521 myOutImageProgram = initProgram (theGlContext, aBasicVertShader, myOutImageShader);
1522 if (myOutImageProgram.IsNull())
1524 return safeFailBack ("Failed to initialize display shader program", theGlContext);
1529 if (myRaytraceInitStatus == OpenGl_RT_NONE || aToRebuildShaders)
1531 for (Standard_Integer anIndex = 0; anIndex < 2; ++anIndex)
1533 Handle(OpenGl_ShaderProgram)& aShaderProgram =
1534 (anIndex == 0) ? myRaytraceProgram : myPostFSAAProgram;
1536 theGlContext->BindProgram (aShaderProgram);
1538 aShaderProgram->SetSampler (theGlContext,
1539 "uSceneMinPointTexture", OpenGl_RT_SceneMinPointTexture);
1540 aShaderProgram->SetSampler (theGlContext,
1541 "uSceneMaxPointTexture", OpenGl_RT_SceneMaxPointTexture);
1542 aShaderProgram->SetSampler (theGlContext,
1543 "uSceneNodeInfoTexture", OpenGl_RT_SceneNodeInfoTexture);
1544 aShaderProgram->SetSampler (theGlContext,
1545 "uGeometryVertexTexture", OpenGl_RT_GeometryVertexTexture);
1546 aShaderProgram->SetSampler (theGlContext,
1547 "uGeometryNormalTexture", OpenGl_RT_GeometryNormalTexture);
1548 aShaderProgram->SetSampler (theGlContext,
1549 "uGeometryTexCrdTexture", OpenGl_RT_GeometryTexCrdTexture);
1550 aShaderProgram->SetSampler (theGlContext,
1551 "uGeometryTriangTexture", OpenGl_RT_GeometryTriangTexture);
1552 aShaderProgram->SetSampler (theGlContext,
1553 "uSceneTransformTexture", OpenGl_RT_SceneTransformTexture);
1554 aShaderProgram->SetSampler (theGlContext,
1555 "uEnvironmentMapTexture", OpenGl_RT_EnvironmentMapTexture);
1556 aShaderProgram->SetSampler (theGlContext,
1557 "uRaytraceMaterialTexture", OpenGl_RT_RaytraceMaterialTexture);
1558 aShaderProgram->SetSampler (theGlContext,
1559 "uRaytraceLightSrcTexture", OpenGl_RT_RaytraceLightSrcTexture);
1563 aShaderProgram->SetSampler (theGlContext,
1564 "uFSAAInputTexture", OpenGl_RT_FsaaInputTexture);
1568 aShaderProgram->SetSampler (theGlContext,
1569 "uAccumTexture", OpenGl_RT_PrevAccumTexture);
1572 myUniformLocations[anIndex][OpenGl_RT_aPosition] =
1573 aShaderProgram->GetAttributeLocation (theGlContext, "occVertex");
1575 myUniformLocations[anIndex][OpenGl_RT_uOriginLB] =
1576 aShaderProgram->GetUniformLocation (theGlContext, "uOriginLB");
1577 myUniformLocations[anIndex][OpenGl_RT_uOriginRB] =
1578 aShaderProgram->GetUniformLocation (theGlContext, "uOriginRB");
1579 myUniformLocations[anIndex][OpenGl_RT_uOriginLT] =
1580 aShaderProgram->GetUniformLocation (theGlContext, "uOriginLT");
1581 myUniformLocations[anIndex][OpenGl_RT_uOriginRT] =
1582 aShaderProgram->GetUniformLocation (theGlContext, "uOriginRT");
1583 myUniformLocations[anIndex][OpenGl_RT_uDirectLB] =
1584 aShaderProgram->GetUniformLocation (theGlContext, "uDirectLB");
1585 myUniformLocations[anIndex][OpenGl_RT_uDirectRB] =
1586 aShaderProgram->GetUniformLocation (theGlContext, "uDirectRB");
1587 myUniformLocations[anIndex][OpenGl_RT_uDirectLT] =
1588 aShaderProgram->GetUniformLocation (theGlContext, "uDirectLT");
1589 myUniformLocations[anIndex][OpenGl_RT_uDirectRT] =
1590 aShaderProgram->GetUniformLocation (theGlContext, "uDirectRT");
1591 myUniformLocations[anIndex][OpenGl_RT_uViewPrMat] =
1592 aShaderProgram->GetUniformLocation (theGlContext, "uViewMat");
1593 myUniformLocations[anIndex][OpenGl_RT_uUnviewMat] =
1594 aShaderProgram->GetUniformLocation (theGlContext, "uUnviewMat");
1596 myUniformLocations[anIndex][OpenGl_RT_uSceneRad] =
1597 aShaderProgram->GetUniformLocation (theGlContext, "uSceneRadius");
1598 myUniformLocations[anIndex][OpenGl_RT_uSceneEps] =
1599 aShaderProgram->GetUniformLocation (theGlContext, "uSceneEpsilon");
1600 myUniformLocations[anIndex][OpenGl_RT_uLightCount] =
1601 aShaderProgram->GetUniformLocation (theGlContext, "uLightCount");
1602 myUniformLocations[anIndex][OpenGl_RT_uLightAmbnt] =
1603 aShaderProgram->GetUniformLocation (theGlContext, "uGlobalAmbient");
1605 myUniformLocations[anIndex][OpenGl_RT_uOffsetX] =
1606 aShaderProgram->GetUniformLocation (theGlContext, "uOffsetX");
1607 myUniformLocations[anIndex][OpenGl_RT_uOffsetY] =
1608 aShaderProgram->GetUniformLocation (theGlContext, "uOffsetY");
1609 myUniformLocations[anIndex][OpenGl_RT_uSamples] =
1610 aShaderProgram->GetUniformLocation (theGlContext, "uSamples");
1612 myUniformLocations[anIndex][OpenGl_RT_uTexSamplersArray] =
1613 aShaderProgram->GetUniformLocation (theGlContext, "uTextureSamplers");
1615 myUniformLocations[anIndex][OpenGl_RT_uShadowsEnabled] =
1616 aShaderProgram->GetUniformLocation (theGlContext, "uShadowsEnabled");
1617 myUniformLocations[anIndex][OpenGl_RT_uReflectEnabled] =
1618 aShaderProgram->GetUniformLocation (theGlContext, "uReflectEnabled");
1619 myUniformLocations[anIndex][OpenGl_RT_uSphereMapEnabled] =
1620 aShaderProgram->GetUniformLocation (theGlContext, "uSphereMapEnabled");
1621 myUniformLocations[anIndex][OpenGl_RT_uSphereMapForBack] =
1622 aShaderProgram->GetUniformLocation (theGlContext, "uSphereMapForBack");
1623 myUniformLocations[anIndex][OpenGl_RT_uBlockedRngEnabled] =
1624 aShaderProgram->GetUniformLocation (theGlContext, "uBlockedRngEnabled");
1626 myUniformLocations[anIndex][OpenGl_RT_uWinSizeX] =
1627 aShaderProgram->GetUniformLocation (theGlContext, "uWinSizeX");
1628 myUniformLocations[anIndex][OpenGl_RT_uWinSizeY] =
1629 aShaderProgram->GetUniformLocation (theGlContext, "uWinSizeY");
1631 myUniformLocations[anIndex][OpenGl_RT_uSampleWeight] =
1632 aShaderProgram->GetUniformLocation (theGlContext, "uSampleWeight");
1633 myUniformLocations[anIndex][OpenGl_RT_uFrameRndSeed] =
1634 aShaderProgram->GetUniformLocation (theGlContext, "uFrameRndSeed");
1636 myUniformLocations[anIndex][OpenGl_RT_uRenderImage] =
1637 aShaderProgram->GetUniformLocation (theGlContext, "uRenderImage");
1638 myUniformLocations[anIndex][OpenGl_RT_uOffsetImage] =
1639 aShaderProgram->GetUniformLocation (theGlContext, "uOffsetImage");
1641 myUniformLocations[anIndex][OpenGl_RT_uBackColorTop] =
1642 aShaderProgram->GetUniformLocation (theGlContext, "uBackColorTop");
1643 myUniformLocations[anIndex][OpenGl_RT_uBackColorBot] =
1644 aShaderProgram->GetUniformLocation (theGlContext, "uBackColorBot");
1647 theGlContext->BindProgram (myOutImageProgram);
1649 myOutImageProgram->SetSampler (theGlContext,
1650 "uInputTexture", OpenGl_RT_PrevAccumTexture);
1652 myOutImageProgram->SetSampler (theGlContext,
1653 "uDepthTexture", OpenGl_RT_RaytraceDepthTexture);
1655 theGlContext->BindProgram (NULL);
1658 if (myRaytraceInitStatus != OpenGl_RT_NONE)
1660 return myRaytraceInitStatus == OpenGl_RT_INIT;
1663 const GLfloat aVertices[] = { -1.f, -1.f, 0.f,
1670 myRaytraceScreenQuad.Init (theGlContext, 3, 6, aVertices);
1672 myRaytraceInitStatus = OpenGl_RT_INIT; // initialized in normal way
1674 return Standard_True;
1677 // =======================================================================
1678 // function : nullifyResource
1679 // purpose : Releases OpenGL resource
1680 // =======================================================================
1682 inline void nullifyResource (const Handle(OpenGl_Context)& theGlContext, Handle(T)& theResource)
1684 if (!theResource.IsNull())
1686 theResource->Release (theGlContext.operator->());
1687 theResource.Nullify();
1691 // =======================================================================
1692 // function : releaseRaytraceResources
1693 // purpose : Releases OpenGL/GLSL shader programs
1694 // =======================================================================
1695 void OpenGl_View::releaseRaytraceResources (const Handle(OpenGl_Context)& theGlContext, const Standard_Boolean theToRebuild)
1697 // release shader resources
1698 nullifyResource (theGlContext, myRaytraceShader);
1699 nullifyResource (theGlContext, myPostFSAAShader);
1701 nullifyResource (theGlContext, myRaytraceProgram);
1702 nullifyResource (theGlContext, myPostFSAAProgram);
1703 nullifyResource (theGlContext, myOutImageProgram);
1705 if (!theToRebuild) // complete release
1707 myRaytraceFBO1[0]->Release (theGlContext.operator->());
1708 myRaytraceFBO1[1]->Release (theGlContext.operator->());
1709 myRaytraceFBO2[0]->Release (theGlContext.operator->());
1710 myRaytraceFBO2[1]->Release (theGlContext.operator->());
1712 nullifyResource (theGlContext, myRaytraceOutputTexture[0]);
1713 nullifyResource (theGlContext, myRaytraceOutputTexture[1]);
1715 nullifyResource (theGlContext, myRaytraceTileOffsetsTexture);
1716 nullifyResource (theGlContext, myRaytraceVisualErrorTexture);
1718 nullifyResource (theGlContext, mySceneNodeInfoTexture);
1719 nullifyResource (theGlContext, mySceneMinPointTexture);
1720 nullifyResource (theGlContext, mySceneMaxPointTexture);
1722 nullifyResource (theGlContext, myGeometryVertexTexture);
1723 nullifyResource (theGlContext, myGeometryNormalTexture);
1724 nullifyResource (theGlContext, myGeometryTexCrdTexture);
1725 nullifyResource (theGlContext, myGeometryTriangTexture);
1726 nullifyResource (theGlContext, mySceneTransformTexture);
1728 nullifyResource (theGlContext, myRaytraceLightSrcTexture);
1729 nullifyResource (theGlContext, myRaytraceMaterialTexture);
1731 myRaytraceGeometry.ReleaseResources (theGlContext);
1733 if (myRaytraceScreenQuad.IsValid ())
1735 myRaytraceScreenQuad.Release (theGlContext.operator->());
1740 // =======================================================================
1741 // function : updateRaytraceBuffers
1742 // purpose : Updates auxiliary OpenGL frame buffers.
1743 // =======================================================================
1744 Standard_Boolean OpenGl_View::updateRaytraceBuffers (const Standard_Integer theSizeX,
1745 const Standard_Integer theSizeY,
1746 const Handle(OpenGl_Context)& theGlContext)
1748 // Auxiliary buffers are not used.
1749 if (!myRaytraceParameters.GlobalIllumination && !myRenderParams.IsAntialiasingEnabled)
1751 myRaytraceFBO1[0]->Release (theGlContext.operator->());
1752 myRaytraceFBO2[0]->Release (theGlContext.operator->());
1753 myRaytraceFBO1[1]->Release (theGlContext.operator->());
1754 myRaytraceFBO2[1]->Release (theGlContext.operator->());
1756 return Standard_True;
1759 myRaytraceFBO1[0]->InitLazy (theGlContext, theSizeX, theSizeY, GL_RGBA32F, myFboDepthFormat);
1760 myRaytraceFBO2[0]->InitLazy (theGlContext, theSizeX, theSizeY, GL_RGBA32F, myFboDepthFormat);
1762 // Init second set of buffers for stereographic rendering.
1763 if (myCamera->ProjectionType() == Graphic3d_Camera::Projection_Stereo)
1765 myRaytraceFBO1[1]->InitLazy (theGlContext, theSizeX, theSizeY, GL_RGBA32F, myFboDepthFormat);
1766 myRaytraceFBO2[1]->InitLazy (theGlContext, theSizeX, theSizeY, GL_RGBA32F, myFboDepthFormat);
1770 myRaytraceFBO1[1]->Release (theGlContext.operator->());
1771 myRaytraceFBO2[1]->Release (theGlContext.operator->());
1774 myTileSampler.SetSize (theSizeX, theSizeY);
1776 if (myRaytraceTileOffsetsTexture.IsNull())
1778 myRaytraceOutputTexture[0] = new OpenGl_Texture();
1779 myRaytraceOutputTexture[1] = new OpenGl_Texture();
1781 myRaytraceTileOffsetsTexture = new OpenGl_Texture();
1782 myRaytraceVisualErrorTexture = new OpenGl_Texture();
1785 if (myRaytraceOutputTexture[0]->SizeX() / 3 != theSizeX
1786 || myRaytraceOutputTexture[0]->SizeY() / 2 != theSizeY)
1788 // Due to limitations of OpenGL image load-store extension
1789 // atomic operations are supported only for single-channel
1790 // images, so we define GL_R32F image. It is used as array
1791 // of 6D floating point vectors:
1792 // 0 - R color channel
1793 // 1 - G color channel
1794 // 2 - B color channel
1795 // 3 - hit time transformed into OpenGL NDC space
1796 // 4 - luminance accumulated for odd samples only
1797 myRaytraceOutputTexture[0]->InitRectangle (theGlContext,
1798 theSizeX * 3, theSizeY * 2, OpenGl_TextureFormat::Create<GLfloat, 1>());
1800 myRaytraceVisualErrorTexture->Init (theGlContext,
1801 GL_R32I, GL_RED_INTEGER, GL_INT, myTileSampler.NbTilesX(), myTileSampler.NbTilesY(), Graphic3d_TOT_2D);
1803 myRaytraceTileOffsetsTexture->Init (theGlContext,
1804 GL_RG32I, GL_RG_INTEGER, GL_INT, myTileSampler.NbTilesX(), myTileSampler.NbTilesY(), Graphic3d_TOT_2D);
1807 if (myCamera->ProjectionType() == Graphic3d_Camera::Projection_Stereo)
1809 if (myRaytraceOutputTexture[1]->SizeX() / 3 != theSizeX
1810 || myRaytraceOutputTexture[1]->SizeY() / 2 != theSizeY)
1812 myRaytraceOutputTexture[1]->InitRectangle (theGlContext,
1813 theSizeX * 3, theSizeY * 2, OpenGl_TextureFormat::Create<GLfloat, 1>());
1818 myRaytraceOutputTexture[1]->Release (theGlContext.operator->());
1821 return Standard_True;
1824 // =======================================================================
1825 // function : updateCamera
1826 // purpose : Generates viewing rays for corners of screen quad
1827 // =======================================================================
1828 void OpenGl_View::updateCamera (const OpenGl_Mat4& theOrientation,
1829 const OpenGl_Mat4& theViewMapping,
1830 OpenGl_Vec3* theOrigins,
1831 OpenGl_Vec3* theDirects,
1832 OpenGl_Mat4& theViewPr,
1833 OpenGl_Mat4& theUnview)
1835 // compute view-projection matrix
1836 theViewPr = theViewMapping * theOrientation;
1838 // compute inverse view-projection matrix
1839 theViewPr.Inverted (theUnview);
1841 Standard_Integer aOriginIndex = 0;
1842 Standard_Integer aDirectIndex = 0;
1844 for (Standard_Integer aY = -1; aY <= 1; aY += 2)
1846 for (Standard_Integer aX = -1; aX <= 1; aX += 2)
1848 OpenGl_Vec4 aOrigin (GLfloat(aX),
1853 aOrigin = theUnview * aOrigin;
1855 aOrigin.x() = aOrigin.x() / aOrigin.w();
1856 aOrigin.y() = aOrigin.y() / aOrigin.w();
1857 aOrigin.z() = aOrigin.z() / aOrigin.w();
1859 OpenGl_Vec4 aDirect (GLfloat(aX),
1864 aDirect = theUnview * aDirect;
1866 aDirect.x() = aDirect.x() / aDirect.w();
1867 aDirect.y() = aDirect.y() / aDirect.w();
1868 aDirect.z() = aDirect.z() / aDirect.w();
1870 aDirect = aDirect - aOrigin;
1872 theOrigins[aOriginIndex++] = OpenGl_Vec3 (static_cast<GLfloat> (aOrigin.x()),
1873 static_cast<GLfloat> (aOrigin.y()),
1874 static_cast<GLfloat> (aOrigin.z()));
1876 theDirects[aDirectIndex++] = OpenGl_Vec3 (static_cast<GLfloat> (aDirect.x()),
1877 static_cast<GLfloat> (aDirect.y()),
1878 static_cast<GLfloat> (aDirect.z()));
1883 // =======================================================================
1884 // function : uploadRaytraceData
1885 // purpose : Uploads ray-trace data to the GPU
1886 // =======================================================================
1887 Standard_Boolean OpenGl_View::uploadRaytraceData (const Handle(OpenGl_Context)& theGlContext)
1889 if (!theGlContext->IsGlGreaterEqual (3, 1))
1891 #ifdef RAY_TRACE_PRINT_INFO
1892 std::cout << "Error: OpenGL version is less than 3.1" << std::endl;
1894 return Standard_False;
1897 myAccumFrames = 0; // accumulation should be restarted
1899 /////////////////////////////////////////////////////////////////////////////
1900 // Prepare OpenGL textures
1902 if (theGlContext->arbTexBindless != NULL)
1904 // If OpenGL driver supports bindless textures we need
1905 // to get unique 64- bit handles for using on the GPU
1906 if (!myRaytraceGeometry.UpdateTextureHandles (theGlContext))
1908 #ifdef RAY_TRACE_PRINT_INFO
1909 std::cout << "Error: Failed to get OpenGL texture handles" << std::endl;
1911 return Standard_False;
1915 /////////////////////////////////////////////////////////////////////////////
1916 // Create OpenGL BVH buffers
1918 if (mySceneNodeInfoTexture.IsNull()) // create scene BVH buffers
1920 mySceneNodeInfoTexture = new OpenGl_TextureBufferArb;
1921 mySceneMinPointTexture = new OpenGl_TextureBufferArb;
1922 mySceneMaxPointTexture = new OpenGl_TextureBufferArb;
1923 mySceneTransformTexture = new OpenGl_TextureBufferArb;
1925 if (!mySceneNodeInfoTexture->Create (theGlContext)
1926 || !mySceneMinPointTexture->Create (theGlContext)
1927 || !mySceneMaxPointTexture->Create (theGlContext)
1928 || !mySceneTransformTexture->Create (theGlContext))
1930 #ifdef RAY_TRACE_PRINT_INFO
1931 std::cout << "Error: Failed to create scene BVH buffers" << std::endl;
1933 return Standard_False;
1937 if (myGeometryVertexTexture.IsNull()) // create geometry buffers
1939 myGeometryVertexTexture = new OpenGl_TextureBufferArb;
1940 myGeometryNormalTexture = new OpenGl_TextureBufferArb;
1941 myGeometryTexCrdTexture = new OpenGl_TextureBufferArb;
1942 myGeometryTriangTexture = new OpenGl_TextureBufferArb;
1944 if (!myGeometryVertexTexture->Create (theGlContext)
1945 || !myGeometryNormalTexture->Create (theGlContext)
1946 || !myGeometryTexCrdTexture->Create (theGlContext)
1947 || !myGeometryTriangTexture->Create (theGlContext))
1949 #ifdef RAY_TRACE_PRINT_INFO
1950 std::cout << "Error: Failed to create buffers for triangulation data" << std::endl;
1952 return Standard_False;
1956 if (myRaytraceMaterialTexture.IsNull()) // create material buffer
1958 myRaytraceMaterialTexture = new OpenGl_TextureBufferArb;
1960 if (!myRaytraceMaterialTexture->Create (theGlContext))
1962 #ifdef RAY_TRACE_PRINT_INFO
1963 std::cout << "Error: Failed to create buffers for material data" << std::endl;
1965 return Standard_False;
1969 /////////////////////////////////////////////////////////////////////////////
1970 // Write transform buffer
1972 BVH_Mat4f* aNodeTransforms = new BVH_Mat4f[myRaytraceGeometry.Size()];
1974 bool aResult = true;
1976 for (Standard_Integer anElemIndex = 0; anElemIndex < myRaytraceGeometry.Size(); ++anElemIndex)
1978 OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
1979 myRaytraceGeometry.Objects().ChangeValue (anElemIndex).operator->());
1981 const BVH_Transform<Standard_ShortReal, 4>* aTransform =
1982 dynamic_cast<const BVH_Transform<Standard_ShortReal, 4>* > (aTriangleSet->Properties().operator->());
1984 Standard_ASSERT_RETURN (aTransform != NULL,
1985 "OpenGl_TriangleSet does not contain transform", Standard_False);
1987 aNodeTransforms[anElemIndex] = aTransform->Inversed();
1990 aResult &= mySceneTransformTexture->Init (theGlContext, 4,
1991 myRaytraceGeometry.Size() * 4, reinterpret_cast<const GLfloat*> (aNodeTransforms));
1993 delete [] aNodeTransforms;
1995 /////////////////////////////////////////////////////////////////////////////
1996 // Write geometry and bottom-level BVH buffers
1998 Standard_Size aTotalVerticesNb = 0;
1999 Standard_Size aTotalElementsNb = 0;
2000 Standard_Size aTotalBVHNodesNb = 0;
2002 for (Standard_Integer anElemIndex = 0; anElemIndex < myRaytraceGeometry.Size(); ++anElemIndex)
2004 OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
2005 myRaytraceGeometry.Objects().ChangeValue (anElemIndex).operator->());
2007 Standard_ASSERT_RETURN (aTriangleSet != NULL,
2008 "Error: Failed to get triangulation of OpenGL element", Standard_False);
2010 aTotalVerticesNb += aTriangleSet->Vertices.size();
2011 aTotalElementsNb += aTriangleSet->Elements.size();
2013 Standard_ASSERT_RETURN (!aTriangleSet->QuadBVH().IsNull(),
2014 "Error: Failed to get bottom-level BVH of OpenGL element", Standard_False);
2016 aTotalBVHNodesNb += aTriangleSet->QuadBVH()->NodeInfoBuffer().size();
2019 aTotalBVHNodesNb += myRaytraceGeometry.QuadBVH()->NodeInfoBuffer().size();
2021 if (aTotalBVHNodesNb != 0)
2023 aResult &= mySceneNodeInfoTexture->Init (
2024 theGlContext, 4, GLsizei (aTotalBVHNodesNb), static_cast<const GLuint*> (NULL));
2025 aResult &= mySceneMinPointTexture->Init (
2026 theGlContext, 3, GLsizei (aTotalBVHNodesNb), static_cast<const GLfloat*> (NULL));
2027 aResult &= mySceneMaxPointTexture->Init (
2028 theGlContext, 3, GLsizei (aTotalBVHNodesNb), static_cast<const GLfloat*> (NULL));
2033 #ifdef RAY_TRACE_PRINT_INFO
2034 std::cout << "Error: Failed to upload buffers for bottom-level scene BVH" << std::endl;
2036 return Standard_False;
2039 if (aTotalElementsNb != 0)
2041 aResult &= myGeometryTriangTexture->Init (
2042 theGlContext, 4, GLsizei (aTotalElementsNb), static_cast<const GLuint*> (NULL));
2045 if (aTotalVerticesNb != 0)
2047 aResult &= myGeometryVertexTexture->Init (
2048 theGlContext, 3, GLsizei (aTotalVerticesNb), static_cast<const GLfloat*> (NULL));
2049 aResult &= myGeometryNormalTexture->Init (
2050 theGlContext, 3, GLsizei (aTotalVerticesNb), static_cast<const GLfloat*> (NULL));
2051 aResult &= myGeometryTexCrdTexture->Init (
2052 theGlContext, 2, GLsizei (aTotalVerticesNb), static_cast<const GLfloat*> (NULL));
2057 #ifdef RAY_TRACE_PRINT_INFO
2058 std::cout << "Error: Failed to upload buffers for scene geometry" << std::endl;
2060 return Standard_False;
2063 const QuadBvhHandle& aBVH = myRaytraceGeometry.QuadBVH();
2065 if (aBVH->Length() > 0)
2067 aResult &= mySceneNodeInfoTexture->SubData (theGlContext, 0, aBVH->Length(),
2068 reinterpret_cast<const GLuint*> (&aBVH->NodeInfoBuffer().front()));
2069 aResult &= mySceneMinPointTexture->SubData (theGlContext, 0, aBVH->Length(),
2070 reinterpret_cast<const GLfloat*> (&aBVH->MinPointBuffer().front()));
2071 aResult &= mySceneMaxPointTexture->SubData (theGlContext, 0, aBVH->Length(),
2072 reinterpret_cast<const GLfloat*> (&aBVH->MaxPointBuffer().front()));
2075 for (Standard_Integer aNodeIdx = 0; aNodeIdx < aBVH->Length(); ++aNodeIdx)
2077 if (!aBVH->IsOuter (aNodeIdx))
2080 OpenGl_TriangleSet* aTriangleSet = myRaytraceGeometry.TriangleSet (aNodeIdx);
2082 Standard_ASSERT_RETURN (aTriangleSet != NULL,
2083 "Error: Failed to get triangulation of OpenGL element", Standard_False);
2085 Standard_Integer aBVHOffset = myRaytraceGeometry.AccelerationOffset (aNodeIdx);
2087 Standard_ASSERT_RETURN (aBVHOffset != OpenGl_RaytraceGeometry::INVALID_OFFSET,
2088 "Error: Failed to get offset for bottom-level BVH", Standard_False);
2090 const Standard_Integer aBvhBuffersSize = aTriangleSet->QuadBVH()->Length();
2092 if (aBvhBuffersSize != 0)
2094 aResult &= mySceneNodeInfoTexture->SubData (theGlContext, aBVHOffset, aBvhBuffersSize,
2095 reinterpret_cast<const GLuint*> (&aTriangleSet->QuadBVH()->NodeInfoBuffer().front()));
2096 aResult &= mySceneMinPointTexture->SubData (theGlContext, aBVHOffset, aBvhBuffersSize,
2097 reinterpret_cast<const GLfloat*> (&aTriangleSet->QuadBVH()->MinPointBuffer().front()));
2098 aResult &= mySceneMaxPointTexture->SubData (theGlContext, aBVHOffset, aBvhBuffersSize,
2099 reinterpret_cast<const GLfloat*> (&aTriangleSet->QuadBVH()->MaxPointBuffer().front()));
2103 #ifdef RAY_TRACE_PRINT_INFO
2104 std::cout << "Error: Failed to upload buffers for bottom-level scene BVHs" << std::endl;
2106 return Standard_False;
2110 const Standard_Integer aVerticesOffset = myRaytraceGeometry.VerticesOffset (aNodeIdx);
2112 Standard_ASSERT_RETURN (aVerticesOffset != OpenGl_RaytraceGeometry::INVALID_OFFSET,
2113 "Error: Failed to get offset for triangulation vertices of OpenGL element", Standard_False);
2115 if (!aTriangleSet->Vertices.empty())
2117 aResult &= myGeometryNormalTexture->SubData (theGlContext, aVerticesOffset,
2118 GLsizei (aTriangleSet->Normals.size()), reinterpret_cast<const GLfloat*> (&aTriangleSet->Normals.front()));
2119 aResult &= myGeometryTexCrdTexture->SubData (theGlContext, aVerticesOffset,
2120 GLsizei (aTriangleSet->TexCrds.size()), reinterpret_cast<const GLfloat*> (&aTriangleSet->TexCrds.front()));
2121 aResult &= myGeometryVertexTexture->SubData (theGlContext, aVerticesOffset,
2122 GLsizei (aTriangleSet->Vertices.size()), reinterpret_cast<const GLfloat*> (&aTriangleSet->Vertices.front()));
2125 const Standard_Integer anElementsOffset = myRaytraceGeometry.ElementsOffset (aNodeIdx);
2127 Standard_ASSERT_RETURN (anElementsOffset != OpenGl_RaytraceGeometry::INVALID_OFFSET,
2128 "Error: Failed to get offset for triangulation elements of OpenGL element", Standard_False);
2130 if (!aTriangleSet->Elements.empty())
2132 aResult &= myGeometryTriangTexture->SubData (theGlContext, anElementsOffset, GLsizei (aTriangleSet->Elements.size()),
2133 reinterpret_cast<const GLuint*> (&aTriangleSet->Elements.front()));
2138 #ifdef RAY_TRACE_PRINT_INFO
2139 std::cout << "Error: Failed to upload triangulation buffers for OpenGL element" << std::endl;
2141 return Standard_False;
2145 /////////////////////////////////////////////////////////////////////////////
2146 // Write material buffer
2148 if (myRaytraceGeometry.Materials.size() != 0)
2150 aResult &= myRaytraceMaterialTexture->Init (theGlContext, 4,
2151 GLsizei (myRaytraceGeometry.Materials.size() * 18), myRaytraceGeometry.Materials.front().Packed());
2155 #ifdef RAY_TRACE_PRINT_INFO
2156 std::cout << "Error: Failed to upload material buffer" << std::endl;
2158 return Standard_False;
2162 myIsRaytraceDataValid = myRaytraceGeometry.Objects().Size() != 0;
2164 #ifdef RAY_TRACE_PRINT_INFO
2166 Standard_ShortReal aMemTrgUsed = 0.f;
2167 Standard_ShortReal aMemBvhUsed = 0.f;
2169 for (Standard_Integer anElemIdx = 0; anElemIdx < myRaytraceGeometry.Size(); ++anElemIdx)
2171 OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (myRaytraceGeometry.Objects()(anElemIdx).get());
2173 aMemTrgUsed += static_cast<Standard_ShortReal> (
2174 aTriangleSet->Vertices.size() * sizeof (BVH_Vec3f));
2175 aMemTrgUsed += static_cast<Standard_ShortReal> (
2176 aTriangleSet->Normals.size() * sizeof (BVH_Vec3f));
2177 aMemTrgUsed += static_cast<Standard_ShortReal> (
2178 aTriangleSet->TexCrds.size() * sizeof (BVH_Vec2f));
2179 aMemTrgUsed += static_cast<Standard_ShortReal> (
2180 aTriangleSet->Elements.size() * sizeof (BVH_Vec4i));
2182 aMemBvhUsed += static_cast<Standard_ShortReal> (
2183 aTriangleSet->QuadBVH()->NodeInfoBuffer().size() * sizeof (BVH_Vec4i));
2184 aMemBvhUsed += static_cast<Standard_ShortReal> (
2185 aTriangleSet->QuadBVH()->MinPointBuffer().size() * sizeof (BVH_Vec3f));
2186 aMemBvhUsed += static_cast<Standard_ShortReal> (
2187 aTriangleSet->QuadBVH()->MaxPointBuffer().size() * sizeof (BVH_Vec3f));
2190 aMemBvhUsed += static_cast<Standard_ShortReal> (
2191 myRaytraceGeometry.QuadBVH()->NodeInfoBuffer().size() * sizeof (BVH_Vec4i));
2192 aMemBvhUsed += static_cast<Standard_ShortReal> (
2193 myRaytraceGeometry.QuadBVH()->MinPointBuffer().size() * sizeof (BVH_Vec3f));
2194 aMemBvhUsed += static_cast<Standard_ShortReal> (
2195 myRaytraceGeometry.QuadBVH()->MaxPointBuffer().size() * sizeof (BVH_Vec3f));
2197 std::cout << "GPU Memory Used (Mb):\n"
2198 << "\tFor mesh: " << aMemTrgUsed / 1048576 << "\n"
2199 << "\tFor BVHs: " << aMemBvhUsed / 1048576 << "\n";
2206 // =======================================================================
2207 // function : updateRaytraceLightSources
2208 // purpose : Updates 3D scene light sources for ray-tracing
2209 // =======================================================================
2210 Standard_Boolean OpenGl_View::updateRaytraceLightSources (const OpenGl_Mat4& theInvModelView, const Handle(OpenGl_Context)& theGlContext)
2212 myRaytraceGeometry.Sources.clear();
2214 myRaytraceGeometry.Ambient = BVH_Vec4f (0.0f, 0.0f, 0.0f, 0.0f);
2216 OpenGl_ListOfLight::Iterator aLightIter (myShadingModel == Graphic3d_TOSM_NONE ? myNoShadingLight : myLights);
2217 for (; aLightIter.More(); aLightIter.Next())
2219 const OpenGl_Light& aLight = aLightIter.Value();
2221 if (aLight.Type == Graphic3d_TOLS_AMBIENT)
2223 myRaytraceGeometry.Ambient += BVH_Vec4f (aLight.Color.r() * aLight.Intensity,
2224 aLight.Color.g() * aLight.Intensity,
2225 aLight.Color.b() * aLight.Intensity,
2230 BVH_Vec4f aDiffuse (aLight.Color.r() * aLight.Intensity,
2231 aLight.Color.g() * aLight.Intensity,
2232 aLight.Color.b() * aLight.Intensity,
2235 BVH_Vec4f aPosition (-aLight.Direction.x(),
2236 -aLight.Direction.y(),
2237 -aLight.Direction.z(),
2240 if (aLight.Type != Graphic3d_TOLS_DIRECTIONAL)
2242 aPosition = BVH_Vec4f (aLight.Position.x(),
2243 aLight.Position.y(),
2244 aLight.Position.z(),
2247 // store smoothing radius in w-component
2248 aDiffuse.w() = Max (aLight.Smoothness, 0.f);
2252 // store cosine of smoothing angle in w-component
2253 aDiffuse.w() = cosf (Min (Max (aLight.Smoothness, 0.f), static_cast<Standard_ShortReal> (M_PI / 2.0)));
2256 if (aLight.IsHeadlight)
2258 aPosition = theInvModelView * aPosition;
2261 myRaytraceGeometry.Sources.push_back (OpenGl_RaytraceLight (aDiffuse, aPosition));
2264 if (myRaytraceLightSrcTexture.IsNull()) // create light source buffer
2266 myRaytraceLightSrcTexture = new OpenGl_TextureBufferArb;
2268 if (!myRaytraceLightSrcTexture->Create (theGlContext))
2270 #ifdef RAY_TRACE_PRINT_INFO
2271 std::cout << "Error: Failed to create light source buffer" << std::endl;
2273 return Standard_False;
2277 if (myRaytraceGeometry.Sources.size() != 0)
2279 const GLfloat* aDataPtr = myRaytraceGeometry.Sources.front().Packed();
2280 if (!myRaytraceLightSrcTexture->Init (theGlContext, 4, GLsizei (myRaytraceGeometry.Sources.size() * 2), aDataPtr))
2282 #ifdef RAY_TRACE_PRINT_INFO
2283 std::cout << "Error: Failed to upload light source buffer" << std::endl;
2285 return Standard_False;
2289 return Standard_True;
2292 // =======================================================================
2293 // function : updateRaytraceEnvironmentMap
2294 // purpose : Updates environment map for ray-tracing
2295 // =======================================================================
2296 Standard_Boolean OpenGl_View::updateRaytraceEnvironmentMap (const Handle(OpenGl_Context)& theGlContext)
2298 Standard_Boolean aResult = Standard_True;
2300 if (!myToUpdateEnvironmentMap)
2305 Handle(OpenGl_ShaderProgram) aPrograms[] = { myRaytraceProgram,
2306 myPostFSAAProgram };
2308 for (Standard_Integer anIdx = 0; anIdx < 2; ++anIdx)
2310 if (!aPrograms[anIdx].IsNull())
2312 aResult &= theGlContext->BindProgram (aPrograms[anIdx]);
2314 if (!myTextureEnv.IsNull())
2316 myTextureEnv->Bind (theGlContext,
2317 GL_TEXTURE0 + OpenGl_RT_EnvironmentMapTexture);
2319 aResult &= aPrograms[anIdx]->SetUniform (theGlContext,
2320 myUniformLocations[anIdx][OpenGl_RT_uSphereMapEnabled], 1);
2324 aResult &= aPrograms[anIdx]->SetUniform (theGlContext,
2325 myUniformLocations[anIdx][OpenGl_RT_uSphereMapEnabled], 0);
2330 myToUpdateEnvironmentMap = Standard_False;
2332 theGlContext->BindProgram (NULL);
2337 // =======================================================================
2338 // function : setUniformState
2339 // purpose : Sets uniform state for the given ray-tracing shader program
2340 // =======================================================================
2341 Standard_Boolean OpenGl_View::setUniformState (const Standard_Integer theProgramId,
2342 const Standard_Integer theWinSizeX,
2343 const Standard_Integer theWinSizeY,
2344 const Handle(OpenGl_Context)& theGlContext)
2346 // Get projection state
2347 OpenGl_MatrixState<Standard_ShortReal>& aCntxProjectionState = theGlContext->ProjectionState;
2349 OpenGl_Mat4 aViewPrjMat;
2350 OpenGl_Mat4 anUnviewMat;
2351 OpenGl_Vec3 aOrigins[4];
2352 OpenGl_Vec3 aDirects[4];
2354 updateCamera (myCamera->OrientationMatrixF(),
2355 aCntxProjectionState.Current(),
2361 Handle(OpenGl_ShaderProgram)& theProgram = theProgramId == 0
2363 : myPostFSAAProgram;
2365 if (theProgram.IsNull())
2367 return Standard_False;
2371 theProgram->SetUniform (theGlContext,
2372 myUniformLocations[theProgramId][OpenGl_RT_uOriginLB], aOrigins[0]);
2373 theProgram->SetUniform (theGlContext,
2374 myUniformLocations[theProgramId][OpenGl_RT_uOriginRB], aOrigins[1]);
2375 theProgram->SetUniform (theGlContext,
2376 myUniformLocations[theProgramId][OpenGl_RT_uOriginLT], aOrigins[2]);
2377 theProgram->SetUniform (theGlContext,
2378 myUniformLocations[theProgramId][OpenGl_RT_uOriginRT], aOrigins[3]);
2379 theProgram->SetUniform (theGlContext,
2380 myUniformLocations[theProgramId][OpenGl_RT_uDirectLB], aDirects[0]);
2381 theProgram->SetUniform (theGlContext,
2382 myUniformLocations[theProgramId][OpenGl_RT_uDirectRB], aDirects[1]);
2383 theProgram->SetUniform (theGlContext,
2384 myUniformLocations[theProgramId][OpenGl_RT_uDirectLT], aDirects[2]);
2385 theProgram->SetUniform (theGlContext,
2386 myUniformLocations[theProgramId][OpenGl_RT_uDirectRT], aDirects[3]);
2387 theProgram->SetUniform (theGlContext,
2388 myUniformLocations[theProgramId][OpenGl_RT_uViewPrMat], aViewPrjMat);
2389 theProgram->SetUniform (theGlContext,
2390 myUniformLocations[theProgramId][OpenGl_RT_uUnviewMat], anUnviewMat);
2392 // Set ray-tracing intersection parameters
2393 theProgram->SetUniform (theGlContext,
2394 myUniformLocations[theProgramId][OpenGl_RT_uSceneRad], myRaytraceSceneRadius);
2395 theProgram->SetUniform (theGlContext,
2396 myUniformLocations[theProgramId][OpenGl_RT_uSceneEps], myRaytraceSceneEpsilon);
2398 const Standard_Integer aLightSourceBufferSize =
2399 static_cast<Standard_Integer> (myRaytraceGeometry.Sources.size());
2401 // Set ray-tracing light source parameters
2402 theProgram->SetUniform (theGlContext,
2403 myUniformLocations[theProgramId][OpenGl_RT_uLightCount], aLightSourceBufferSize);
2404 theProgram->SetUniform (theGlContext,
2405 myUniformLocations[theProgramId][OpenGl_RT_uLightAmbnt], myRaytraceGeometry.Ambient);
2407 // Enable/disable run time rendering effects
2408 theProgram->SetUniform (theGlContext,
2409 myUniformLocations[theProgramId][OpenGl_RT_uShadowsEnabled], myRenderParams.IsShadowEnabled ? 1 : 0);
2410 theProgram->SetUniform (theGlContext,
2411 myUniformLocations[theProgramId][OpenGl_RT_uReflectEnabled], myRenderParams.IsReflectionEnabled ? 1 : 0);
2413 // Set screen dimensions
2414 myRaytraceProgram->SetUniform (theGlContext,
2415 myUniformLocations[theProgramId][OpenGl_RT_uWinSizeX], theWinSizeX);
2416 myRaytraceProgram->SetUniform (theGlContext,
2417 myUniformLocations[theProgramId][OpenGl_RT_uWinSizeY], theWinSizeY);
2419 if (myRenderParams.IsGlobalIlluminationEnabled) // if Monte-Carlo sampling enabled
2421 theProgram->SetUniform (theGlContext,
2422 myUniformLocations[theProgramId][OpenGl_RT_uBlockedRngEnabled], myRenderParams.CoherentPathTracingMode ? 1 : 0);
2425 // Set array of 64-bit texture handles
2426 if (theGlContext->arbTexBindless != NULL && myRaytraceGeometry.HasTextures())
2428 const std::vector<GLuint64>& aTextures = myRaytraceGeometry.TextureHandles();
2430 theProgram->SetUniform (theGlContext, myUniformLocations[theProgramId][OpenGl_RT_uTexSamplersArray],
2431 static_cast<GLsizei> (aTextures.size()), reinterpret_cast<const OpenGl_Vec2u*> (&aTextures.front()));
2434 // Set background colors (only gradient background supported)
2435 if (myBgGradientArray != NULL && myBgGradientArray->IsDefined())
2437 theProgram->SetUniform (theGlContext,
2438 myUniformLocations[theProgramId][OpenGl_RT_uBackColorTop], myBgGradientArray->GradientColor (0));
2439 theProgram->SetUniform (theGlContext,
2440 myUniformLocations[theProgramId][OpenGl_RT_uBackColorBot], myBgGradientArray->GradientColor (1));
2444 const OpenGl_Vec4& aBackColor = myBgColor;
2446 theProgram->SetUniform (theGlContext,
2447 myUniformLocations[theProgramId][OpenGl_RT_uBackColorTop], aBackColor);
2448 theProgram->SetUniform (theGlContext,
2449 myUniformLocations[theProgramId][OpenGl_RT_uBackColorBot], aBackColor);
2452 theProgram->SetUniform (theGlContext,
2453 myUniformLocations[theProgramId][OpenGl_RT_uSphereMapForBack], myRenderParams.UseEnvironmentMapBackground ? 1 : 0);
2455 return Standard_True;
2458 // =======================================================================
2459 // function : bindRaytraceTextures
2460 // purpose : Binds ray-trace textures to corresponding texture units
2461 // =======================================================================
2462 void OpenGl_View::bindRaytraceTextures (const Handle(OpenGl_Context)& theGlContext)
2464 if (myRaytraceParameters.AdaptiveScreenSampling)
2466 #if !defined(GL_ES_VERSION_2_0)
2467 theGlContext->core42->glBindImageTexture (OpenGl_RT_OutputImageLft,
2468 myRaytraceOutputTexture[0]->TextureId(), 0, GL_TRUE, 0, GL_READ_WRITE, GL_R32F);
2469 theGlContext->core42->glBindImageTexture (OpenGl_RT_OutputImageRgh,
2470 myRaytraceOutputTexture[1]->TextureId(), 0, GL_TRUE, 0, GL_READ_WRITE, GL_R32F);
2472 theGlContext->core42->glBindImageTexture (OpenGl_RT_VisualErrorImage,
2473 myRaytraceVisualErrorTexture->TextureId(), 0, GL_TRUE, 0, GL_READ_WRITE, GL_R32I);
2474 theGlContext->core42->glBindImageTexture (OpenGl_RT_TileOffsetsImage,
2475 myRaytraceTileOffsetsTexture->TextureId(), 0, GL_TRUE, 0, GL_READ_ONLY, GL_RG32I);
2479 mySceneMinPointTexture->BindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_SceneMinPointTexture);
2480 mySceneMaxPointTexture->BindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_SceneMaxPointTexture);
2481 mySceneNodeInfoTexture->BindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_SceneNodeInfoTexture);
2482 myGeometryVertexTexture->BindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryVertexTexture);
2483 myGeometryNormalTexture->BindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryNormalTexture);
2484 myGeometryTexCrdTexture->BindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryTexCrdTexture);
2485 myGeometryTriangTexture->BindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryTriangTexture);
2486 mySceneTransformTexture->BindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_SceneTransformTexture);
2487 myRaytraceMaterialTexture->BindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_RaytraceMaterialTexture);
2488 myRaytraceLightSrcTexture->BindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_RaytraceLightSrcTexture);
2491 // =======================================================================
2492 // function : unbindRaytraceTextures
2493 // purpose : Unbinds ray-trace textures from corresponding texture units
2494 // =======================================================================
2495 void OpenGl_View::unbindRaytraceTextures (const Handle(OpenGl_Context)& theGlContext)
2497 mySceneMinPointTexture->UnbindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_SceneMinPointTexture);
2498 mySceneMaxPointTexture->UnbindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_SceneMaxPointTexture);
2499 mySceneNodeInfoTexture->UnbindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_SceneNodeInfoTexture);
2500 myGeometryVertexTexture->UnbindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryVertexTexture);
2501 myGeometryNormalTexture->UnbindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryNormalTexture);
2502 myGeometryTexCrdTexture->UnbindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryTexCrdTexture);
2503 myGeometryTriangTexture->UnbindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryTriangTexture);
2504 mySceneTransformTexture->UnbindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_SceneTransformTexture);
2505 myRaytraceMaterialTexture->UnbindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_RaytraceMaterialTexture);
2506 myRaytraceLightSrcTexture->UnbindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_RaytraceLightSrcTexture);
2508 theGlContext->core15fwd->glActiveTexture (GL_TEXTURE0);
2511 // =======================================================================
2512 // function : runRaytraceShaders
2513 // purpose : Runs ray-tracing shader programs
2514 // =======================================================================
2515 Standard_Boolean OpenGl_View::runRaytraceShaders (const Standard_Integer theSizeX,
2516 const Standard_Integer theSizeY,
2517 Graphic3d_Camera::Projection theProjection,
2518 OpenGl_FrameBuffer* theReadDrawFbo,
2519 const Handle(OpenGl_Context)& theGlContext)
2521 Standard_Boolean aResult = theGlContext->BindProgram (myRaytraceProgram);
2523 aResult &= setUniformState (0,
2528 if (myRaytraceParameters.GlobalIllumination) // path tracing
2530 aResult &= runPathtrace (theProjection, theReadDrawFbo, theGlContext);
2532 else // Whitted-style ray-tracing
2534 aResult &= runRaytrace (theSizeX, theSizeY, theProjection, theReadDrawFbo, theGlContext);
2540 // =======================================================================
2541 // function : runRaytrace
2542 // purpose : Runs Whitted-style ray-tracing
2543 // =======================================================================
2544 Standard_Boolean OpenGl_View::runRaytrace (const Standard_Integer theSizeX,
2545 const Standard_Integer theSizeY,
2546 Graphic3d_Camera::Projection theProjection,
2547 OpenGl_FrameBuffer* theReadDrawFbo,
2548 const Handle(OpenGl_Context)& theGlContext)
2550 Standard_Boolean aResult = Standard_True;
2552 bindRaytraceTextures (theGlContext);
2554 Handle(OpenGl_FrameBuffer) aRenderImageFramebuffer;
2555 Handle(OpenGl_FrameBuffer) aDepthSourceFramebuffer;
2557 // Choose proper set of frame buffers for stereo rendering
2558 const Standard_Integer aFBOIdx (theProjection == Graphic3d_Camera::Projection_MonoRightEye);
2560 if (myRenderParams.IsAntialiasingEnabled) // if second FSAA pass is used
2562 myRaytraceFBO1[aFBOIdx]->BindBuffer (theGlContext);
2564 glClear (GL_DEPTH_BUFFER_BIT); // render the image with depth
2567 theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
2569 if (myRenderParams.IsAntialiasingEnabled)
2571 glDisable (GL_DEPTH_TEST); // improve jagged edges without depth buffer
2573 // bind ray-tracing output image as input
2574 myRaytraceFBO1[aFBOIdx]->ColorTexture()->Bind (theGlContext, GL_TEXTURE0 + OpenGl_RT_FsaaInputTexture);
2576 aResult &= theGlContext->BindProgram (myPostFSAAProgram);
2578 aResult &= setUniformState (1 /* FSAA ID */,
2583 // Perform multi-pass adaptive FSAA using ping-pong technique.
2584 // We use 'FLIPTRI' sampling pattern changing for every pixel
2585 // (3 additional samples per pixel, the 1st sample is already
2586 // available from initial ray-traced image).
2587 for (Standard_Integer anIt = 1; anIt < 4; ++anIt)
2589 GLfloat aOffsetX = 1.f / theSizeX;
2590 GLfloat aOffsetY = 1.f / theSizeY;
2608 aResult &= myPostFSAAProgram->SetUniform (theGlContext,
2609 myUniformLocations[1][OpenGl_RT_uSamples], anIt + 1);
2610 aResult &= myPostFSAAProgram->SetUniform (theGlContext,
2611 myUniformLocations[1][OpenGl_RT_uOffsetX], aOffsetX);
2612 aResult &= myPostFSAAProgram->SetUniform (theGlContext,
2613 myUniformLocations[1][OpenGl_RT_uOffsetY], aOffsetY);
2615 Handle(OpenGl_FrameBuffer)& aFramebuffer = anIt % 2
2616 ? myRaytraceFBO2[aFBOIdx]
2617 : myRaytraceFBO1[aFBOIdx];
2619 aFramebuffer->BindBuffer (theGlContext);
2621 // perform adaptive FSAA pass
2622 theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
2624 aFramebuffer->ColorTexture()->Bind (theGlContext, GL_TEXTURE0 + OpenGl_RT_FsaaInputTexture);
2627 aRenderImageFramebuffer = myRaytraceFBO2[aFBOIdx];
2628 aDepthSourceFramebuffer = myRaytraceFBO1[aFBOIdx];
2630 glEnable (GL_DEPTH_TEST);
2632 // Display filtered image
2633 theGlContext->BindProgram (myOutImageProgram);
2635 if (theReadDrawFbo != NULL)
2637 theReadDrawFbo->BindBuffer (theGlContext);
2641 aRenderImageFramebuffer->UnbindBuffer (theGlContext);
2644 aRenderImageFramebuffer->ColorTexture()->Bind (
2645 theGlContext, GL_TEXTURE0 + OpenGl_RT_PrevAccumTexture);
2647 aDepthSourceFramebuffer->DepthStencilTexture()->Bind (
2648 theGlContext, GL_TEXTURE0 + OpenGl_RT_RaytraceDepthTexture);
2650 // copy the output image with depth values
2651 theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
2653 aDepthSourceFramebuffer->DepthStencilTexture()->Unbind (
2654 theGlContext, GL_TEXTURE0 + OpenGl_RT_RaytraceDepthTexture);
2656 aRenderImageFramebuffer->ColorTexture()->Unbind (
2657 theGlContext, GL_TEXTURE0 + OpenGl_RT_PrevAccumTexture);
2660 unbindRaytraceTextures (theGlContext);
2662 theGlContext->BindProgram (NULL);
2667 // =======================================================================
2668 // function : runPathtrace
2669 // purpose : Runs path tracing shader
2670 // =======================================================================
2671 Standard_Boolean OpenGl_View::runPathtrace (const Graphic3d_Camera::Projection theProjection,
2672 OpenGl_FrameBuffer* theReadDrawFbo,
2673 const Handle(OpenGl_Context)& theGlContext)
2675 Standard_Boolean aResult = Standard_True;
2677 if (myRaytraceParameters.AdaptiveScreenSampling)
2679 if (myAccumFrames == 0)
2681 myTileSampler.Reset(); // reset tile sampler to its initial state
2684 // We upload tile offset texture each 4 frames in order
2685 // to minimize overhead of additional memory bandwidth.
2686 // Adaptive sampling is starting after first 10 frames.
2687 if (myAccumFrames % 4 == 0)
2689 myTileSampler.Upload (theGlContext, myRaytraceTileOffsetsTexture, myAccumFrames > 10);
2693 bindRaytraceTextures (theGlContext);
2695 Handle(OpenGl_FrameBuffer) aRenderImageFramebuffer;
2696 Handle(OpenGl_FrameBuffer) aDepthSourceFramebuffer;
2697 Handle(OpenGl_FrameBuffer) anAccumImageFramebuffer;
2699 // Choose proper set of frame buffers for stereo rendering
2700 const Standard_Integer aFBOIdx (theProjection == Graphic3d_Camera::Projection_MonoRightEye);
2702 const Standard_Integer anImageId = (aFBOIdx != 0)
2703 ? OpenGl_RT_OutputImageRgh
2704 : OpenGl_RT_OutputImageLft;
2706 aRenderImageFramebuffer = myAccumFrames % 2 ? myRaytraceFBO1[aFBOIdx] : myRaytraceFBO2[aFBOIdx];
2707 anAccumImageFramebuffer = myAccumFrames % 2 ? myRaytraceFBO2[aFBOIdx] : myRaytraceFBO1[aFBOIdx];
2709 aDepthSourceFramebuffer = aRenderImageFramebuffer;
2711 anAccumImageFramebuffer->ColorTexture()->Bind (
2712 theGlContext, GL_TEXTURE0 + OpenGl_RT_PrevAccumTexture);
2714 aRenderImageFramebuffer->BindBuffer (theGlContext);
2716 if (myAccumFrames == 0)
2718 myRNG.SetSeed(); // start RNG from beginning
2721 // Clear adaptive screen sampling images
2722 if (myRaytraceParameters.AdaptiveScreenSampling)
2724 #if !defined(GL_ES_VERSION_2_0)
2725 if (myAccumFrames == 0)
2727 theGlContext->core44->glClearTexImage (myRaytraceOutputTexture[aFBOIdx]->TextureId(), 0, GL_RED, GL_FLOAT, NULL);
2730 theGlContext->core44->glClearTexImage (myRaytraceVisualErrorTexture->TextureId(), 0, GL_RED_INTEGER, GL_INT, NULL);
2734 // Set frame accumulation weight
2735 myRaytraceProgram->SetUniform (theGlContext,
2736 myUniformLocations[0][OpenGl_RT_uSampleWeight], 1.f / (myAccumFrames + 1));
2738 // Set random number generator seed
2739 myRaytraceProgram->SetUniform (theGlContext,
2740 myUniformLocations[0][OpenGl_RT_uFrameRndSeed], static_cast<Standard_Integer> (myRNG.NextInt() >> 2));
2742 // Set image uniforms for render program
2743 myRaytraceProgram->SetUniform (theGlContext,
2744 myUniformLocations[0][OpenGl_RT_uRenderImage], anImageId);
2745 myRaytraceProgram->SetUniform (theGlContext,
2746 myUniformLocations[0][OpenGl_RT_uOffsetImage], OpenGl_RT_TileOffsetsImage);
2748 glDisable (GL_DEPTH_TEST);
2750 // Generate for the given RNG seed
2751 theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
2753 // Output accumulated path traced image
2754 theGlContext->BindProgram (myOutImageProgram);
2756 if (myRaytraceParameters.AdaptiveScreenSampling)
2758 // Set uniforms for display program
2759 myOutImageProgram->SetUniform (theGlContext, "uRenderImage", anImageId);
2760 myOutImageProgram->SetUniform (theGlContext, "uAccumFrames", myAccumFrames);
2761 myOutImageProgram->SetUniform (theGlContext, "uVarianceImage", OpenGl_RT_VisualErrorImage);
2762 myOutImageProgram->SetUniform (theGlContext, "uDebugAdaptive", myRenderParams.ShowSamplingTiles ? 1 : 0);
2765 if (theReadDrawFbo != NULL)
2767 theReadDrawFbo->BindBuffer (theGlContext);
2771 aRenderImageFramebuffer->UnbindBuffer (theGlContext);
2774 aRenderImageFramebuffer->ColorTexture()->Bind (
2775 theGlContext, GL_TEXTURE0 + OpenGl_RT_PrevAccumTexture);
2777 glEnable (GL_DEPTH_TEST);
2779 // Copy accumulated image with correct depth values
2780 theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
2782 aRenderImageFramebuffer->ColorTexture()->Unbind (
2783 theGlContext, GL_TEXTURE0 + OpenGl_RT_PrevAccumTexture);
2785 if (myRaytraceParameters.AdaptiveScreenSampling)
2787 myRaytraceVisualErrorTexture->Bind (theGlContext);
2789 // Download visual error map from the GPU and build
2790 // adjusted tile offsets for optimal image sampling
2791 myTileSampler.GrabVarianceMap (theGlContext);
2794 unbindRaytraceTextures (theGlContext);
2796 theGlContext->BindProgram (NULL);
2801 // =======================================================================
2802 // function : raytrace
2803 // purpose : Redraws the window using OpenGL/GLSL ray-tracing
2804 // =======================================================================
2805 Standard_Boolean OpenGl_View::raytrace (const Standard_Integer theSizeX,
2806 const Standard_Integer theSizeY,
2807 Graphic3d_Camera::Projection theProjection,
2808 OpenGl_FrameBuffer* theReadDrawFbo,
2809 const Handle(OpenGl_Context)& theGlContext)
2811 if (!initRaytraceResources (theGlContext))
2813 return Standard_False;
2816 if (!updateRaytraceBuffers (theSizeX, theSizeY, theGlContext))
2818 return Standard_False;
2821 if (!updateRaytraceEnvironmentMap (theGlContext))
2823 return Standard_False;
2826 OpenGl_Mat4 aLightSourceMatrix;
2828 // Get inversed model-view matrix for transforming lights
2829 myCamera->OrientationMatrixF().Inverted (aLightSourceMatrix);
2831 if (!updateRaytraceLightSources (aLightSourceMatrix, theGlContext))
2833 return Standard_False;
2836 // Generate image using Whitted-style ray-tracing or path tracing
2837 if (myIsRaytraceDataValid)
2839 myRaytraceScreenQuad.BindVertexAttrib (theGlContext, Graphic3d_TOA_POS);
2841 if (!myRaytraceGeometry.AcquireTextures (theGlContext))
2843 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR,
2844 0, GL_DEBUG_SEVERITY_MEDIUM, "Error: Failed to acquire OpenGL image textures");
2847 glDisable (GL_BLEND);
2849 const Standard_Boolean aResult = runRaytraceShaders (theSizeX,
2857 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR,
2858 0, GL_DEBUG_SEVERITY_MEDIUM, "Error: Failed to execute ray-tracing shaders");
2861 if (!myRaytraceGeometry.ReleaseTextures (theGlContext))
2863 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR,
2864 0, GL_DEBUG_SEVERITY_MEDIUM, "Error: Failed to release OpenGL image textures");
2867 myRaytraceScreenQuad.UnbindVertexAttrib (theGlContext, Graphic3d_TOA_POS);
2870 return Standard_True;