0028811: Visualization - merge texturing support into AIS_Shape class and get rid...
[occt.git] / src / OpenGl / OpenGl_View_Raytrace.cxx
... / ...
CommitLineData
1// Created on: 2015-02-20
2// Created by: Denis BOGOLEPOV
3// Copyright (c) 2015 OPEN CASCADE SAS
4//
5// This file is part of Open CASCADE Technology software library.
6//
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.
12//
13// Alternatively, this file may be used under the terms of Open CASCADE
14// commercial license or contractual agreement.
15
16#include <OpenGl_View.hxx>
17
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>
24
25#include "../Shaders/Shaders_RaytraceBase_vs.pxx"
26#include "../Shaders/Shaders_RaytraceBase_fs.pxx"
27#include "../Shaders/Shaders_PathtraceBase_fs.pxx"
28#include "../Shaders/Shaders_RaytraceRender_fs.pxx"
29#include "../Shaders/Shaders_RaytraceSmooth_fs.pxx"
30#include "../Shaders/Shaders_Display_fs.pxx"
31
32using namespace OpenGl_Raytrace;
33
34//! Use this macro to output ray-tracing debug info
35// #define RAY_TRACE_PRINT_INFO
36
37#ifdef RAY_TRACE_PRINT_INFO
38 #include <OSD_Timer.hxx>
39#endif
40
41namespace
42{
43 static const OpenGl_Vec4 THE_WHITE_COLOR (1.0f, 1.0f, 1.0f, 1.0f);
44 static const OpenGl_Vec4 THE_BLACK_COLOR (0.0f, 0.0f, 0.0f, 1.0f);
45
46 //! Operator returning TRUE for positional light sources.
47 struct IsLightPositional
48 {
49 bool operator() (const OpenGl_Light& theLight)
50 {
51 return theLight.Type != Graphic3d_TOLS_DIRECTIONAL;
52 }
53 };
54
55 //! Operator returning TRUE for any non-ambient light sources.
56 struct IsNotAmbient
57 {
58 bool operator() (const OpenGl_Light& theLight)
59 {
60 return theLight.Type != Graphic3d_TOLS_AMBIENT;
61 }
62 };
63}
64
65// =======================================================================
66// function : updateRaytraceGeometry
67// purpose : Updates 3D scene geometry for ray-tracing
68// =======================================================================
69Standard_Boolean OpenGl_View::updateRaytraceGeometry (const RaytraceUpdateMode theMode,
70 const Standard_Integer theViewId,
71 const Handle(OpenGl_Context)& theGlContext)
72{
73 // In 'check' mode (OpenGl_GUM_CHECK) the scene geometry is analyzed for
74 // modifications. This is light-weight procedure performed on each frame
75 if (theMode == OpenGl_GUM_CHECK)
76 {
77 if (myRaytraceLayerListState != myZLayers.ModificationStateOfRaytracable())
78 {
79 return updateRaytraceGeometry (OpenGl_GUM_PREPARE, theViewId, theGlContext);
80 }
81 }
82 else if (theMode == OpenGl_GUM_PREPARE)
83 {
84 myRaytraceGeometry.ClearMaterials();
85
86 myArrayToTrianglesMap.clear();
87
88 myIsRaytraceDataValid = Standard_False;
89 }
90
91 // The set of processed structures (reflected to ray-tracing)
92 // This set is used to remove out-of-date records from the
93 // hash map of structures
94 std::set<const OpenGl_Structure*> anElements;
95
96 // Set to store all currently visible OpenGL primitive arrays
97 // applicable for ray-tracing
98 std::set<Standard_Size> anArrayIDs;
99
100 // Set to store all non-raytracable elements allowing tracking
101 // of changes in OpenGL scene (only for path tracing)
102 std::set<Standard_Integer> aNonRaytraceIDs;
103
104 const OpenGl_Layer& aLayer = myZLayers.Layer (Graphic3d_ZLayerId_Default);
105
106 if (aLayer.NbStructures() != 0)
107 {
108 const OpenGl_ArrayOfIndexedMapOfStructure& aStructArray = aLayer.ArrayOfStructures();
109
110 for (Standard_Integer anIndex = 0; anIndex < aStructArray.Length(); ++anIndex)
111 {
112 for (OpenGl_IndexedMapOfStructure::Iterator aStructIt (aStructArray (anIndex)); aStructIt.More(); aStructIt.Next())
113 {
114 const OpenGl_Structure* aStructure = aStructIt.Value();
115
116 if (theMode == OpenGl_GUM_CHECK)
117 {
118 if (toUpdateStructure (aStructure))
119 {
120 return updateRaytraceGeometry (OpenGl_GUM_PREPARE, theViewId, theGlContext);
121 }
122 else if (aStructure->IsVisible() && myRaytraceParameters.GlobalIllumination)
123 {
124 aNonRaytraceIDs.insert (aStructure->highlight ? aStructure->Id : -aStructure->Id);
125 }
126 }
127 else if (theMode == OpenGl_GUM_PREPARE)
128 {
129 if (!aStructure->IsRaytracable() || !aStructure->IsVisible())
130 {
131 continue;
132 }
133 else if (!aStructure->ViewAffinity.IsNull() && !aStructure->ViewAffinity->IsVisible (theViewId))
134 {
135 continue;
136 }
137
138 for (OpenGl_Structure::GroupIterator aGroupIter (aStructure->Groups()); aGroupIter.More(); aGroupIter.Next())
139 {
140 // Extract OpenGL elements from the group (primitives arrays)
141 for (const OpenGl_ElementNode* aNode = aGroupIter.Value()->FirstNode(); aNode != NULL; aNode = aNode->next)
142 {
143 OpenGl_PrimitiveArray* aPrimArray = dynamic_cast<OpenGl_PrimitiveArray*> (aNode->elem);
144
145 if (aPrimArray != NULL)
146 {
147 anArrayIDs.insert (aPrimArray->GetUID());
148 }
149 }
150 }
151 }
152 else if (theMode == OpenGl_GUM_REBUILD)
153 {
154 if (!aStructure->IsRaytracable())
155 {
156 continue;
157 }
158 else if (addRaytraceStructure (aStructure, theGlContext))
159 {
160 anElements.insert (aStructure); // structure was processed
161 }
162 }
163 }
164 }
165 }
166
167 if (theMode == OpenGl_GUM_PREPARE)
168 {
169 BVH_ObjectSet<Standard_ShortReal, 3>::BVH_ObjectList anUnchangedObjects;
170
171 // Filter out unchanged objects so only their transformations and materials
172 // will be updated (and newly added objects will be processed from scratch)
173 for (Standard_Integer anObjIdx = 0; anObjIdx < myRaytraceGeometry.Size(); ++anObjIdx)
174 {
175 OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
176 myRaytraceGeometry.Objects().ChangeValue (anObjIdx).operator->());
177
178 if (aTriangleSet == NULL)
179 {
180 continue;
181 }
182
183 if (anArrayIDs.find (aTriangleSet->AssociatedPArrayID()) != anArrayIDs.end())
184 {
185 anUnchangedObjects.Append (myRaytraceGeometry.Objects().Value (anObjIdx));
186
187 myArrayToTrianglesMap[aTriangleSet->AssociatedPArrayID()] = aTriangleSet;
188 }
189 }
190
191 myRaytraceGeometry.Objects() = anUnchangedObjects;
192
193 return updateRaytraceGeometry (OpenGl_GUM_REBUILD, theViewId, theGlContext);
194 }
195 else if (theMode == OpenGl_GUM_REBUILD)
196 {
197 // Actualize the hash map of structures - remove out-of-date records
198 std::map<const OpenGl_Structure*, StructState>::iterator anIter = myStructureStates.begin();
199
200 while (anIter != myStructureStates.end())
201 {
202 if (anElements.find (anIter->first) == anElements.end())
203 {
204 myStructureStates.erase (anIter++);
205 }
206 else
207 {
208 ++anIter;
209 }
210 }
211
212 // Actualize OpenGL layer list state
213 myRaytraceLayerListState = myZLayers.ModificationStateOfRaytracable();
214
215 // Rebuild two-level acceleration structure
216 myRaytraceGeometry.ProcessAcceleration();
217
218 myRaytraceSceneRadius = 2.f /* scale factor */ * std::max (
219 myRaytraceGeometry.Box().CornerMin().cwiseAbs().maxComp(),
220 myRaytraceGeometry.Box().CornerMax().cwiseAbs().maxComp());
221
222 const BVH_Vec3f aSize = myRaytraceGeometry.Box().Size();
223
224 myRaytraceSceneEpsilon = Max (1.0e-6f, 1.0e-4f * aSize.Modulus());
225
226 return uploadRaytraceData (theGlContext);
227 }
228
229 if (myRaytraceParameters.GlobalIllumination)
230 {
231 Standard_Boolean toRestart =
232 aNonRaytraceIDs.size() != myNonRaytraceStructureIDs.size();
233
234 for (std::set<Standard_Integer>::iterator anID = aNonRaytraceIDs.begin(); anID != aNonRaytraceIDs.end() && !toRestart; ++anID)
235 {
236 if (myNonRaytraceStructureIDs.find (*anID) == myNonRaytraceStructureIDs.end())
237 {
238 toRestart = Standard_True;
239 }
240 }
241
242 if (toRestart)
243 {
244 myAccumFrames = 0;
245 }
246
247 myNonRaytraceStructureIDs = aNonRaytraceIDs;
248 }
249
250 return Standard_True;
251}
252
253// =======================================================================
254// function : toUpdateStructure
255// purpose : Checks to see if the structure is modified
256// =======================================================================
257Standard_Boolean OpenGl_View::toUpdateStructure (const OpenGl_Structure* theStructure)
258{
259 if (!theStructure->IsRaytracable())
260 {
261 if (theStructure->ModificationState() > 0)
262 {
263 theStructure->ResetModificationState();
264
265 return Standard_True; // ray-trace element was removed - need to rebuild
266 }
267
268 return Standard_False; // did not contain ray-trace elements
269 }
270
271 std::map<const OpenGl_Structure*, StructState>::iterator aStructState = myStructureStates.find (theStructure);
272
273 if (aStructState == myStructureStates.end() || aStructState->second.StructureState != theStructure->ModificationState())
274 {
275 return Standard_True;
276 }
277 else if (theStructure->InstancedStructure() != NULL)
278 {
279 return aStructState->second.InstancedState != theStructure->InstancedStructure()->ModificationState();
280 }
281
282 return Standard_False;
283}
284
285// =======================================================================
286// function : buildTextureTransform
287// purpose : Constructs texture transformation matrix
288// =======================================================================
289void buildTextureTransform (const Handle(Graphic3d_TextureParams)& theParams, BVH_Mat4f& theMatrix)
290{
291 theMatrix.InitIdentity();
292
293 // Apply scaling
294 const Graphic3d_Vec2& aScale = theParams->Scale();
295
296 theMatrix.ChangeValue (0, 0) *= aScale.x();
297 theMatrix.ChangeValue (1, 0) *= aScale.x();
298 theMatrix.ChangeValue (2, 0) *= aScale.x();
299 theMatrix.ChangeValue (3, 0) *= aScale.x();
300
301 theMatrix.ChangeValue (0, 1) *= aScale.y();
302 theMatrix.ChangeValue (1, 1) *= aScale.y();
303 theMatrix.ChangeValue (2, 1) *= aScale.y();
304 theMatrix.ChangeValue (3, 1) *= aScale.y();
305
306 // Apply translation
307 const Graphic3d_Vec2 aTrans = -theParams->Translation();
308
309 theMatrix.ChangeValue (0, 3) = theMatrix.GetValue (0, 0) * aTrans.x() +
310 theMatrix.GetValue (0, 1) * aTrans.y();
311
312 theMatrix.ChangeValue (1, 3) = theMatrix.GetValue (1, 0) * aTrans.x() +
313 theMatrix.GetValue (1, 1) * aTrans.y();
314
315 theMatrix.ChangeValue (2, 3) = theMatrix.GetValue (2, 0) * aTrans.x() +
316 theMatrix.GetValue (2, 1) * aTrans.y();
317
318 // Apply rotation
319 const Standard_ShortReal aSin = std::sin (
320 -theParams->Rotation() * static_cast<Standard_ShortReal> (M_PI / 180.0));
321 const Standard_ShortReal aCos = std::cos (
322 -theParams->Rotation() * static_cast<Standard_ShortReal> (M_PI / 180.0));
323
324 BVH_Mat4f aRotationMat;
325 aRotationMat.SetValue (0, 0, aCos);
326 aRotationMat.SetValue (1, 1, aCos);
327 aRotationMat.SetValue (0, 1, -aSin);
328 aRotationMat.SetValue (1, 0, aSin);
329
330 theMatrix = theMatrix * aRotationMat;
331}
332
333// =======================================================================
334// function : convertMaterial
335// purpose : Creates ray-tracing material properties
336// =======================================================================
337OpenGl_RaytraceMaterial OpenGl_View::convertMaterial (const OpenGl_AspectFace* theAspect,
338 const Handle(OpenGl_Context)& theGlContext)
339{
340 OpenGl_RaytraceMaterial theMaterial;
341
342 const Graphic3d_MaterialAspect& aSrcMat = theAspect->Aspect()->FrontMaterial();
343 const OpenGl_Vec3& aMatCol = theAspect->Aspect()->InteriorColor();
344 const bool isPhysic = aSrcMat.MaterialType (Graphic3d_MATERIAL_PHYSIC);
345 const float aShine = 128.0f * float(aSrcMat.Shininess());
346
347 // ambient component
348 if (aSrcMat.ReflectionMode (Graphic3d_TOR_AMBIENT))
349 {
350 const OpenGl_Vec3& aSrcAmb = isPhysic ? aSrcMat.AmbientColor() : aMatCol;
351 theMaterial.Ambient = BVH_Vec4f (aSrcAmb * (float )aSrcMat.Ambient(), 1.0f);
352 }
353 else
354 {
355 theMaterial.Ambient = THE_BLACK_COLOR;
356 }
357
358 // diffusion component
359 if (aSrcMat.ReflectionMode (Graphic3d_TOR_DIFFUSE))
360 {
361 const OpenGl_Vec3& aSrcDif = isPhysic ? aSrcMat.DiffuseColor() : aMatCol;
362 theMaterial.Diffuse = BVH_Vec4f (aSrcDif * (float )aSrcMat.Diffuse(), -1.0f); // -1 is no texture
363 }
364 else
365 {
366 theMaterial.Diffuse = BVH_Vec4f (THE_BLACK_COLOR.rgb(), -1.0f);
367 }
368
369 // specular component
370 if (aSrcMat.ReflectionMode (Graphic3d_TOR_SPECULAR))
371 {
372 const OpenGl_Vec3& aSrcSpe = aSrcMat.SpecularColor();
373 const OpenGl_Vec3& aSrcSpe2 = isPhysic ? aSrcSpe : THE_WHITE_COLOR.rgb();
374 theMaterial.Specular = BVH_Vec4f (aSrcSpe2 * (float )aSrcMat.Specular(), aShine);
375
376 const Standard_ShortReal aMaxRefl = Max (theMaterial.Diffuse.x() + theMaterial.Specular.x(),
377 Max (theMaterial.Diffuse.y() + theMaterial.Specular.y(),
378 theMaterial.Diffuse.z() + theMaterial.Specular.z()));
379
380 const Standard_ShortReal aReflectionScale = 0.75f / aMaxRefl;
381
382 // ignore isPhysic here
383 theMaterial.Reflection = BVH_Vec4f (aSrcSpe * (float )aSrcMat.Specular() * aReflectionScale, 0.0f);
384 }
385 else
386 {
387 theMaterial.Specular = BVH_Vec4f (THE_BLACK_COLOR.rgb(), aShine);
388 }
389
390 // emission component
391 if (aSrcMat.ReflectionMode (Graphic3d_TOR_EMISSION))
392 {
393 const OpenGl_Vec3& aSrcEms = isPhysic ? aSrcMat.EmissiveColor() : aMatCol;
394 theMaterial.Emission = BVH_Vec4f (aSrcEms * (float )aSrcMat.Emissive(), 1.0f);
395 }
396 else
397 {
398 theMaterial.Emission = THE_BLACK_COLOR;
399 }
400
401 const float anIndex = (float )aSrcMat.RefractionIndex();
402 theMaterial.Transparency = BVH_Vec4f (aSrcMat.Alpha(), aSrcMat.Transparency(),
403 anIndex == 0 ? 1.0f : anIndex,
404 anIndex == 0 ? 1.0f : 1.0f / anIndex);
405
406 // Serialize physically-based material properties
407 const Graphic3d_BSDF& aBSDF = aSrcMat.BSDF();
408
409 theMaterial.BSDF.Kc = aBSDF.Kc;
410 theMaterial.BSDF.Ks = aBSDF.Ks;
411 theMaterial.BSDF.Kd = BVH_Vec4f (aBSDF.Kd, -1.f); // no texture
412 theMaterial.BSDF.Kt = BVH_Vec4f (aBSDF.Kt, 0.f);
413 theMaterial.BSDF.Le = BVH_Vec4f (aBSDF.Le, 0.f);
414
415 theMaterial.BSDF.Absorption = aBSDF.Absorption;
416
417 theMaterial.BSDF.FresnelCoat = aBSDF.FresnelCoat.Serialize ();
418 theMaterial.BSDF.FresnelBase = aBSDF.FresnelBase.Serialize ();
419
420 // Handle material textures
421 if (theAspect->Aspect()->ToMapTexture())
422 {
423 if (theGlContext->HasRayTracingTextures())
424 {
425 buildTextureTransform (theAspect->TextureParams(), theMaterial.TextureTransform);
426
427 // write texture ID to diffuse w-component
428 theMaterial.Diffuse.w() = theMaterial.BSDF.Kd.w() =
429 static_cast<Standard_ShortReal> (myRaytraceGeometry.AddTexture (theAspect->TextureRes (theGlContext)));
430 }
431 else if (!myIsRaytraceWarnTextures)
432 {
433 const TCollection_ExtendedString aWarnMessage =
434 "Warning: texturing in Ray-Trace requires GL_ARB_bindless_texture extension which is missing. "
435 "Please try to update graphics card driver. At the moment textures will be ignored.";
436
437 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
438 GL_DEBUG_TYPE_PORTABILITY, 0, GL_DEBUG_SEVERITY_HIGH, aWarnMessage);
439
440 myIsRaytraceWarnTextures = Standard_True;
441 }
442 }
443
444 return theMaterial;
445}
446
447// =======================================================================
448// function : addRaytraceStructure
449// purpose : Adds OpenGL structure to ray-traced scene geometry
450// =======================================================================
451Standard_Boolean OpenGl_View::addRaytraceStructure (const OpenGl_Structure* theStructure,
452 const Handle(OpenGl_Context)& theGlContext)
453{
454 if (!theStructure->IsVisible())
455 {
456 myStructureStates[theStructure] = StructState (theStructure);
457
458 return Standard_True;
459 }
460
461 // Get structure material
462 OpenGl_RaytraceMaterial aDefaultMaterial;
463 Standard_Boolean aResult = addRaytraceGroups (theStructure, aDefaultMaterial, theStructure->Transformation(), theGlContext);
464
465 // Process all connected OpenGL structures
466 const OpenGl_Structure* anInstanced = theStructure->InstancedStructure();
467
468 if (anInstanced != NULL && anInstanced->IsRaytracable())
469 {
470 aResult &= addRaytraceGroups (anInstanced, aDefaultMaterial, theStructure->Transformation(), theGlContext);
471 }
472
473 myStructureStates[theStructure] = StructState (theStructure);
474
475 return aResult;
476}
477
478// =======================================================================
479// function : addRaytraceGroups
480// purpose : Adds OpenGL groups to ray-traced scene geometry
481// =======================================================================
482Standard_Boolean OpenGl_View::addRaytraceGroups (const OpenGl_Structure* theStructure,
483 const OpenGl_RaytraceMaterial& theStructMat,
484 const Handle(Geom_Transformation)& theTrsf,
485 const Handle(OpenGl_Context)& theGlContext)
486{
487 OpenGl_Mat4 aMat4;
488 for (OpenGl_Structure::GroupIterator aGroupIter (theStructure->Groups()); aGroupIter.More(); aGroupIter.Next())
489 {
490 // Get group material
491 OpenGl_RaytraceMaterial aGroupMaterial;
492 if (aGroupIter.Value()->AspectFace() != NULL)
493 {
494 aGroupMaterial = convertMaterial (
495 aGroupIter.Value()->AspectFace(), theGlContext);
496 }
497
498 Standard_Integer aMatID = static_cast<Standard_Integer> (myRaytraceGeometry.Materials.size());
499
500 // Use group material if available, otherwise use structure material
501 myRaytraceGeometry.Materials.push_back (
502 aGroupIter.Value()->AspectFace() != NULL ? aGroupMaterial : theStructMat);
503
504 // Add OpenGL elements from group (extract primitives arrays and aspects)
505 for (const OpenGl_ElementNode* aNode = aGroupIter.Value()->FirstNode(); aNode != NULL; aNode = aNode->next)
506 {
507 OpenGl_AspectFace* anAspect = dynamic_cast<OpenGl_AspectFace*> (aNode->elem);
508
509 if (anAspect != NULL)
510 {
511 aMatID = static_cast<Standard_Integer> (myRaytraceGeometry.Materials.size());
512
513 OpenGl_RaytraceMaterial aMaterial = convertMaterial (anAspect, theGlContext);
514
515 myRaytraceGeometry.Materials.push_back (aMaterial);
516 }
517 else
518 {
519 OpenGl_PrimitiveArray* aPrimArray = dynamic_cast<OpenGl_PrimitiveArray*> (aNode->elem);
520
521 if (aPrimArray != NULL)
522 {
523 std::map<Standard_Size, OpenGl_TriangleSet*>::iterator aSetIter = myArrayToTrianglesMap.find (aPrimArray->GetUID());
524
525 if (aSetIter != myArrayToTrianglesMap.end())
526 {
527 OpenGl_TriangleSet* aSet = aSetIter->second;
528 opencascade::handle<BVH_Transform<Standard_ShortReal, 4> > aTransform = new BVH_Transform<Standard_ShortReal, 4>();
529 if (!theTrsf.IsNull())
530 {
531 theTrsf->Trsf().GetMat4 (aMat4);
532 aTransform->SetTransform (aMat4);
533 }
534
535 aSet->SetProperties (aTransform);
536 if (aSet->MaterialIndex() != OpenGl_TriangleSet::INVALID_MATERIAL && aSet->MaterialIndex() != aMatID)
537 {
538 aSet->SetMaterialIndex (aMatID);
539 }
540 }
541 else
542 {
543 if (Handle(OpenGl_TriangleSet) aSet = addRaytracePrimitiveArray (aPrimArray, aMatID, 0))
544 {
545 opencascade::handle<BVH_Transform<Standard_ShortReal, 4> > aTransform = new BVH_Transform<Standard_ShortReal, 4>();
546 if (!theTrsf.IsNull())
547 {
548 theTrsf->Trsf().GetMat4 (aMat4);
549 aTransform->SetTransform (aMat4);
550 }
551
552 aSet->SetProperties (aTransform);
553 myRaytraceGeometry.Objects().Append (aSet);
554 }
555 }
556 }
557 }
558 }
559 }
560
561 return Standard_True;
562}
563
564// =======================================================================
565// function : addRaytracePrimitiveArray
566// purpose : Adds OpenGL primitive array to ray-traced scene geometry
567// =======================================================================
568Handle(OpenGl_TriangleSet) OpenGl_View::addRaytracePrimitiveArray (const OpenGl_PrimitiveArray* theArray,
569 const Standard_Integer theMaterial,
570 const OpenGl_Mat4* theTransform)
571{
572 const Handle(Graphic3d_BoundBuffer)& aBounds = theArray->Bounds();
573 const Handle(Graphic3d_IndexBuffer)& anIndices = theArray->Indices();
574 const Handle(Graphic3d_Buffer)& anAttribs = theArray->Attributes();
575
576 if (theArray->DrawMode() < GL_TRIANGLES
577 #ifndef GL_ES_VERSION_2_0
578 || theArray->DrawMode() > GL_POLYGON
579 #else
580 || theArray->DrawMode() > GL_TRIANGLE_FAN
581 #endif
582 || anAttribs.IsNull())
583 {
584 return Handle(OpenGl_TriangleSet)();
585 }
586
587 OpenGl_Mat4 aNormalMatrix;
588 if (theTransform != NULL)
589 {
590 Standard_ASSERT_RETURN (theTransform->Inverted (aNormalMatrix),
591 "Error: Failed to compute normal transformation matrix", NULL);
592
593 aNormalMatrix.Transpose();
594 }
595
596 Handle(OpenGl_TriangleSet) aSet = new OpenGl_TriangleSet (theArray->GetUID(), myRaytraceBVHBuilder);
597 {
598 aSet->Vertices.reserve (anAttribs->NbElements);
599 aSet->Normals.reserve (anAttribs->NbElements);
600 aSet->TexCrds.reserve (anAttribs->NbElements);
601
602 const size_t aVertFrom = aSet->Vertices.size();
603 for (Standard_Integer anAttribIter = 0; anAttribIter < anAttribs->NbAttributes; ++anAttribIter)
604 {
605 const Graphic3d_Attribute& anAttrib = anAttribs->Attribute (anAttribIter);
606 const size_t anOffset = anAttribs->AttributeOffset (anAttribIter);
607 if (anAttrib.Id == Graphic3d_TOA_POS)
608 {
609 if (anAttrib.DataType == Graphic3d_TOD_VEC3
610 || anAttrib.DataType == Graphic3d_TOD_VEC4)
611 {
612 for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
613 {
614 aSet->Vertices.push_back (
615 *reinterpret_cast<const Graphic3d_Vec3*> (anAttribs->value (aVertIter) + anOffset));
616 }
617 }
618 else if (anAttrib.DataType == Graphic3d_TOD_VEC2)
619 {
620 for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
621 {
622 const Standard_ShortReal* aCoords =
623 reinterpret_cast<const Standard_ShortReal*> (anAttribs->value (aVertIter) + anOffset);
624
625 aSet->Vertices.push_back (BVH_Vec3f (aCoords[0], aCoords[1], 0.0f));
626 }
627 }
628 }
629 else if (anAttrib.Id == Graphic3d_TOA_NORM)
630 {
631 if (anAttrib.DataType == Graphic3d_TOD_VEC3
632 || anAttrib.DataType == Graphic3d_TOD_VEC4)
633 {
634 for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
635 {
636 aSet->Normals.push_back (
637 *reinterpret_cast<const Graphic3d_Vec3*> (anAttribs->value (aVertIter) + anOffset));
638 }
639 }
640 }
641 else if (anAttrib.Id == Graphic3d_TOA_UV)
642 {
643 if (anAttrib.DataType == Graphic3d_TOD_VEC2)
644 {
645 for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
646 {
647 aSet->TexCrds.push_back (
648 *reinterpret_cast<const Graphic3d_Vec2*> (anAttribs->value (aVertIter) + anOffset));
649 }
650 }
651 }
652 }
653
654 if (aSet->Normals.size() != aSet->Vertices.size())
655 {
656 for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
657 {
658 aSet->Normals.push_back (BVH_Vec3f());
659 }
660 }
661
662 if (aSet->TexCrds.size() != aSet->Vertices.size())
663 {
664 for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
665 {
666 aSet->TexCrds.push_back (BVH_Vec2f());
667 }
668 }
669
670 if (theTransform != NULL)
671 {
672 for (size_t aVertIter = aVertFrom; aVertIter < aSet->Vertices.size(); ++aVertIter)
673 {
674 BVH_Vec3f& aVertex = aSet->Vertices[aVertIter];
675
676 BVH_Vec4f aTransVertex = *theTransform *
677 BVH_Vec4f (aVertex.x(), aVertex.y(), aVertex.z(), 1.f);
678
679 aVertex = BVH_Vec3f (aTransVertex.x(), aTransVertex.y(), aTransVertex.z());
680 }
681 for (size_t aVertIter = aVertFrom; aVertIter < aSet->Normals.size(); ++aVertIter)
682 {
683 BVH_Vec3f& aNormal = aSet->Normals[aVertIter];
684
685 BVH_Vec4f aTransNormal = aNormalMatrix *
686 BVH_Vec4f (aNormal.x(), aNormal.y(), aNormal.z(), 0.f);
687
688 aNormal = BVH_Vec3f (aTransNormal.x(), aTransNormal.y(), aTransNormal.z());
689 }
690 }
691
692 if (!aBounds.IsNull())
693 {
694 for (Standard_Integer aBound = 0, aBoundStart = 0; aBound < aBounds->NbBounds; ++aBound)
695 {
696 const Standard_Integer aVertNum = aBounds->Bounds[aBound];
697
698 if (!addRaytraceVertexIndices (*aSet, theMaterial, aVertNum, aBoundStart, *theArray))
699 {
700 aSet.Nullify();
701 return Handle(OpenGl_TriangleSet)();
702 }
703
704 aBoundStart += aVertNum;
705 }
706 }
707 else
708 {
709 const Standard_Integer aVertNum = !anIndices.IsNull() ? anIndices->NbElements : anAttribs->NbElements;
710
711 if (!addRaytraceVertexIndices (*aSet, theMaterial, aVertNum, 0, *theArray))
712 {
713 aSet.Nullify();
714 return Handle(OpenGl_TriangleSet)();
715 }
716 }
717 }
718
719 if (aSet->Size() != 0)
720 {
721 aSet->MarkDirty();
722 }
723
724 return aSet;
725}
726
727// =======================================================================
728// function : addRaytraceVertexIndices
729// purpose : Adds vertex indices to ray-traced scene geometry
730// =======================================================================
731Standard_Boolean OpenGl_View::addRaytraceVertexIndices (OpenGl_TriangleSet& theSet,
732 const Standard_Integer theMatID,
733 const Standard_Integer theCount,
734 const Standard_Integer theOffset,
735 const OpenGl_PrimitiveArray& theArray)
736{
737 switch (theArray.DrawMode())
738 {
739 case GL_TRIANGLES: return addRaytraceTriangleArray (theSet, theMatID, theCount, theOffset, theArray.Indices());
740 case GL_TRIANGLE_FAN: return addRaytraceTriangleFanArray (theSet, theMatID, theCount, theOffset, theArray.Indices());
741 case GL_TRIANGLE_STRIP: return addRaytraceTriangleStripArray (theSet, theMatID, theCount, theOffset, theArray.Indices());
742 #if !defined(GL_ES_VERSION_2_0)
743 case GL_QUAD_STRIP: return addRaytraceQuadrangleStripArray (theSet, theMatID, theCount, theOffset, theArray.Indices());
744 case GL_QUADS: return addRaytraceQuadrangleArray (theSet, theMatID, theCount, theOffset, theArray.Indices());
745 case GL_POLYGON: return addRaytracePolygonArray (theSet, theMatID, theCount, theOffset, theArray.Indices());
746 #endif
747 }
748
749 return Standard_False;
750}
751
752// =======================================================================
753// function : addRaytraceTriangleArray
754// purpose : Adds OpenGL triangle array to ray-traced scene geometry
755// =======================================================================
756Standard_Boolean OpenGl_View::addRaytraceTriangleArray (OpenGl_TriangleSet& theSet,
757 const Standard_Integer theMatID,
758 const Standard_Integer theCount,
759 const Standard_Integer theOffset,
760 const Handle(Graphic3d_IndexBuffer)& theIndices)
761{
762 if (theCount < 3)
763 {
764 return Standard_True;
765 }
766
767 theSet.Elements.reserve (theSet.Elements.size() + theCount / 3);
768
769 if (!theIndices.IsNull())
770 {
771 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; aVert += 3)
772 {
773 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0),
774 theIndices->Index (aVert + 1),
775 theIndices->Index (aVert + 2),
776 theMatID));
777 }
778 }
779 else
780 {
781 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; aVert += 3)
782 {
783 theSet.Elements.push_back (BVH_Vec4i (aVert + 0, aVert + 1, aVert + 2, theMatID));
784 }
785 }
786
787 return Standard_True;
788}
789
790// =======================================================================
791// function : addRaytraceTriangleFanArray
792// purpose : Adds OpenGL triangle fan array to ray-traced scene geometry
793// =======================================================================
794Standard_Boolean OpenGl_View::addRaytraceTriangleFanArray (OpenGl_TriangleSet& theSet,
795 const Standard_Integer theMatID,
796 const Standard_Integer theCount,
797 const Standard_Integer theOffset,
798 const Handle(Graphic3d_IndexBuffer)& theIndices)
799{
800 if (theCount < 3)
801 {
802 return Standard_True;
803 }
804
805 theSet.Elements.reserve (theSet.Elements.size() + theCount - 2);
806
807 if (!theIndices.IsNull())
808 {
809 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
810 {
811 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (theOffset),
812 theIndices->Index (aVert + 1),
813 theIndices->Index (aVert + 2),
814 theMatID));
815 }
816 }
817 else
818 {
819 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
820 {
821 theSet.Elements.push_back (BVH_Vec4i (theOffset,
822 aVert + 1,
823 aVert + 2,
824 theMatID));
825 }
826 }
827
828 return Standard_True;
829}
830
831// =======================================================================
832// function : addRaytraceTriangleStripArray
833// purpose : Adds OpenGL triangle strip array to ray-traced scene geometry
834// =======================================================================
835Standard_Boolean OpenGl_View::addRaytraceTriangleStripArray (OpenGl_TriangleSet& theSet,
836 const Standard_Integer theMatID,
837 const Standard_Integer theCount,
838 const Standard_Integer theOffset,
839 const Handle(Graphic3d_IndexBuffer)& theIndices)
840{
841 if (theCount < 3)
842 {
843 return Standard_True;
844 }
845
846 theSet.Elements.reserve (theSet.Elements.size() + theCount - 2);
847
848 if (!theIndices.IsNull())
849 {
850 for (Standard_Integer aVert = theOffset, aCW = 0; aVert < theOffset + theCount - 2; ++aVert, aCW = (aCW + 1) % 2)
851 {
852 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + (aCW ? 1 : 0)),
853 theIndices->Index (aVert + (aCW ? 0 : 1)),
854 theIndices->Index (aVert + 2),
855 theMatID));
856 }
857 }
858 else
859 {
860 for (Standard_Integer aVert = theOffset, aCW = 0; aVert < theOffset + theCount - 2; ++aVert, aCW = (aCW + 1) % 2)
861 {
862 theSet.Elements.push_back (BVH_Vec4i (aVert + (aCW ? 1 : 0),
863 aVert + (aCW ? 0 : 1),
864 aVert + 2,
865 theMatID));
866 }
867 }
868
869 return Standard_True;
870}
871
872// =======================================================================
873// function : addRaytraceQuadrangleArray
874// purpose : Adds OpenGL quad array to ray-traced scene geometry
875// =======================================================================
876Standard_Boolean OpenGl_View::addRaytraceQuadrangleArray (OpenGl_TriangleSet& theSet,
877 const Standard_Integer theMatID,
878 const Standard_Integer theCount,
879 const Standard_Integer theOffset,
880 const Handle(Graphic3d_IndexBuffer)& theIndices)
881{
882 if (theCount < 4)
883 {
884 return Standard_True;
885 }
886
887 theSet.Elements.reserve (theSet.Elements.size() + theCount / 2);
888
889 if (!theIndices.IsNull())
890 {
891 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 4)
892 {
893 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0),
894 theIndices->Index (aVert + 1),
895 theIndices->Index (aVert + 2),
896 theMatID));
897 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0),
898 theIndices->Index (aVert + 2),
899 theIndices->Index (aVert + 3),
900 theMatID));
901 }
902 }
903 else
904 {
905 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 4)
906 {
907 theSet.Elements.push_back (BVH_Vec4i (aVert + 0, aVert + 1, aVert + 2,
908 theMatID));
909 theSet.Elements.push_back (BVH_Vec4i (aVert + 0, aVert + 2, aVert + 3,
910 theMatID));
911 }
912 }
913
914 return Standard_True;
915}
916
917// =======================================================================
918// function : addRaytraceQuadrangleStripArray
919// purpose : Adds OpenGL quad strip array to ray-traced scene geometry
920// =======================================================================
921Standard_Boolean OpenGl_View::addRaytraceQuadrangleStripArray (OpenGl_TriangleSet& theSet,
922 const Standard_Integer theMatID,
923 const Standard_Integer theCount,
924 const Standard_Integer theOffset,
925 const Handle(Graphic3d_IndexBuffer)& theIndices)
926{
927 if (theCount < 4)
928 {
929 return Standard_True;
930 }
931
932 theSet.Elements.reserve (theSet.Elements.size() + 2 * theCount - 6);
933
934 if (!theIndices.IsNull())
935 {
936 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 2)
937 {
938 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0),
939 theIndices->Index (aVert + 1),
940 theIndices->Index (aVert + 2),
941 theMatID));
942
943 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 1),
944 theIndices->Index (aVert + 3),
945 theIndices->Index (aVert + 2),
946 theMatID));
947 }
948 }
949 else
950 {
951 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 2)
952 {
953 theSet.Elements.push_back (BVH_Vec4i (aVert + 0,
954 aVert + 1,
955 aVert + 2,
956 theMatID));
957
958 theSet.Elements.push_back (BVH_Vec4i (aVert + 1,
959 aVert + 3,
960 aVert + 2,
961 theMatID));
962 }
963 }
964
965 return Standard_True;
966}
967
968// =======================================================================
969// function : addRaytracePolygonArray
970// purpose : Adds OpenGL polygon array to ray-traced scene geometry
971// =======================================================================
972Standard_Boolean OpenGl_View::addRaytracePolygonArray (OpenGl_TriangleSet& theSet,
973 const Standard_Integer theMatID,
974 const Standard_Integer theCount,
975 const Standard_Integer theOffset,
976 const Handle(Graphic3d_IndexBuffer)& theIndices)
977{
978 if (theCount < 3)
979 {
980 return Standard_True;
981 }
982
983 theSet.Elements.reserve (theSet.Elements.size() + theCount - 2);
984
985 if (!theIndices.IsNull())
986 {
987 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
988 {
989 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (theOffset),
990 theIndices->Index (aVert + 1),
991 theIndices->Index (aVert + 2),
992 theMatID));
993 }
994 }
995 else
996 {
997 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
998 {
999 theSet.Elements.push_back (BVH_Vec4i (theOffset,
1000 aVert + 1,
1001 aVert + 2,
1002 theMatID));
1003 }
1004 }
1005
1006 return Standard_True;
1007}
1008
1009const TCollection_AsciiString OpenGl_View::ShaderSource::EMPTY_PREFIX;
1010
1011// =======================================================================
1012// function : Source
1013// purpose : Returns shader source combined with prefix
1014// =======================================================================
1015TCollection_AsciiString OpenGl_View::ShaderSource::Source() const
1016{
1017 const TCollection_AsciiString aVersion = "#version 140";
1018
1019 if (myPrefix.IsEmpty())
1020 {
1021 return aVersion + "\n" + mySource;
1022 }
1023
1024 return aVersion + "\n" + myPrefix + "\n" + mySource;
1025}
1026
1027// =======================================================================
1028// function : LoadFromFiles
1029// purpose : Loads shader source from specified files
1030// =======================================================================
1031Standard_Boolean OpenGl_View::ShaderSource::LoadFromFiles (const TCollection_AsciiString* theFileNames,
1032 const TCollection_AsciiString& thePrefix)
1033{
1034 myError.Clear();
1035 mySource.Clear();
1036 myPrefix = thePrefix;
1037
1038 TCollection_AsciiString aMissingFiles;
1039 for (Standard_Integer anIndex = 0; !theFileNames[anIndex].IsEmpty(); ++anIndex)
1040 {
1041 OSD_File aFile (theFileNames[anIndex]);
1042 if (aFile.Exists())
1043 {
1044 aFile.Open (OSD_ReadOnly, OSD_Protection());
1045 }
1046 if (!aFile.IsOpen())
1047 {
1048 if (!aMissingFiles.IsEmpty())
1049 {
1050 aMissingFiles += ", ";
1051 }
1052 aMissingFiles += TCollection_AsciiString("'") + theFileNames[anIndex] + "'";
1053 continue;
1054 }
1055 else if (!aMissingFiles.IsEmpty())
1056 {
1057 aFile.Close();
1058 continue;
1059 }
1060
1061 TCollection_AsciiString aSource;
1062 aFile.Read (aSource, (Standard_Integer) aFile.Size());
1063 if (!aSource.IsEmpty())
1064 {
1065 mySource += TCollection_AsciiString ("\n") + aSource;
1066 }
1067 aFile.Close();
1068 }
1069
1070 if (!aMissingFiles.IsEmpty())
1071 {
1072 myError = TCollection_AsciiString("Shader files ") + aMissingFiles + " are missing or inaccessible";
1073 return Standard_False;
1074 }
1075 return Standard_True;
1076}
1077
1078// =======================================================================
1079// function : LoadFromStrings
1080// purpose :
1081// =======================================================================
1082Standard_Boolean OpenGl_View::ShaderSource::LoadFromStrings (const TCollection_AsciiString* theStrings,
1083 const TCollection_AsciiString& thePrefix)
1084{
1085 myError.Clear();
1086 mySource.Clear();
1087 myPrefix = thePrefix;
1088
1089 for (Standard_Integer anIndex = 0; !theStrings[anIndex].IsEmpty(); ++anIndex)
1090 {
1091 TCollection_AsciiString aSource = theStrings[anIndex];
1092 if (!aSource.IsEmpty())
1093 {
1094 mySource += TCollection_AsciiString ("\n") + aSource;
1095 }
1096 }
1097 return Standard_True;
1098}
1099
1100// =======================================================================
1101// function : generateShaderPrefix
1102// purpose : Generates shader prefix based on current ray-tracing options
1103// =======================================================================
1104TCollection_AsciiString OpenGl_View::generateShaderPrefix (const Handle(OpenGl_Context)& theGlContext) const
1105{
1106 TCollection_AsciiString aPrefixString =
1107 TCollection_AsciiString ("#define STACK_SIZE ") + TCollection_AsciiString (myRaytraceParameters.StackSize) + "\n" +
1108 TCollection_AsciiString ("#define NB_BOUNCES ") + TCollection_AsciiString (myRaytraceParameters.NbBounces);
1109
1110 if (myRaytraceParameters.TransparentShadows)
1111 {
1112 aPrefixString += TCollection_AsciiString ("\n#define TRANSPARENT_SHADOWS");
1113 }
1114
1115 // If OpenGL driver supports bindless textures and texturing
1116 // is actually used, activate texturing in ray-tracing mode
1117 if (myRaytraceParameters.UseBindlessTextures && theGlContext->arbTexBindless != NULL)
1118 {
1119 aPrefixString += TCollection_AsciiString ("\n#define USE_TEXTURES") +
1120 TCollection_AsciiString ("\n#define MAX_TEX_NUMBER ") + TCollection_AsciiString (OpenGl_RaytraceGeometry::MAX_TEX_NUMBER);
1121 }
1122
1123 if (myRaytraceParameters.GlobalIllumination) // path tracing activated
1124 {
1125 aPrefixString += TCollection_AsciiString ("\n#define PATH_TRACING");
1126
1127 if (myRaytraceParameters.AdaptiveScreenSampling) // adaptive screen sampling requested
1128 {
1129 // to activate the feature we need OpenGL 4.4 and GL_NV_shader_atomic_float extension
1130 if (theGlContext->IsGlGreaterEqual (4, 4) && theGlContext->CheckExtension ("GL_NV_shader_atomic_float"))
1131 {
1132 aPrefixString += TCollection_AsciiString ("\n#define ADAPTIVE_SAMPLING") +
1133 TCollection_AsciiString ("\n#define BLOCK_SIZE ") + TCollection_AsciiString (OpenGl_TileSampler::TileSize());
1134 }
1135 }
1136
1137 if (myRaytraceParameters.TwoSidedBsdfModels) // two-sided BSDFs requested
1138 {
1139 aPrefixString += TCollection_AsciiString ("\n#define TWO_SIDED_BXDF");
1140 }
1141
1142 switch (myRaytraceParameters.ToneMappingMethod)
1143 {
1144 case Graphic3d_ToneMappingMethod_Disabled:
1145 break;
1146 case Graphic3d_ToneMappingMethod_Filmic:
1147 aPrefixString += TCollection_AsciiString ("\n#define TONE_MAPPING_FILMIC");
1148 break;
1149 }
1150 }
1151
1152 if (myRaytraceParameters.DepthOfField)
1153 {
1154 aPrefixString += TCollection_AsciiString("\n#define DEPTH_OF_FIELD");
1155 }
1156
1157 return aPrefixString;
1158}
1159
1160// =======================================================================
1161// function : safeFailBack
1162// purpose : Performs safe exit when shaders initialization fails
1163// =======================================================================
1164Standard_Boolean OpenGl_View::safeFailBack (const TCollection_ExtendedString& theMessage,
1165 const Handle(OpenGl_Context)& theGlContext)
1166{
1167 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1168 GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, theMessage);
1169
1170 myRaytraceInitStatus = OpenGl_RT_FAIL;
1171
1172 releaseRaytraceResources (theGlContext);
1173
1174 return Standard_False;
1175}
1176
1177// =======================================================================
1178// function : initShader
1179// purpose : Creates new shader object with specified source
1180// =======================================================================
1181Handle(OpenGl_ShaderObject) OpenGl_View::initShader (const GLenum theType,
1182 const ShaderSource& theSource,
1183 const Handle(OpenGl_Context)& theGlContext)
1184{
1185 Handle(OpenGl_ShaderObject) aShader = new OpenGl_ShaderObject (theType);
1186
1187 if (!aShader->Create (theGlContext))
1188 {
1189 const TCollection_ExtendedString aMessage = TCollection_ExtendedString ("Error: Failed to create ") +
1190 (theType == GL_VERTEX_SHADER ? "vertex" : "fragment") + " shader object";
1191
1192 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1193 GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, aMessage);
1194
1195 aShader->Release (theGlContext.operator->());
1196
1197 return Handle(OpenGl_ShaderObject)();
1198 }
1199
1200 if (!aShader->LoadSource (theGlContext, theSource.Source()))
1201 {
1202 const TCollection_ExtendedString aMessage = TCollection_ExtendedString ("Error: Failed to set ") +
1203 (theType == GL_VERTEX_SHADER ? "vertex" : "fragment") + " shader source";
1204
1205 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1206 GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, aMessage);
1207
1208 aShader->Release (theGlContext.operator->());
1209
1210 return Handle(OpenGl_ShaderObject)();
1211 }
1212
1213 TCollection_AsciiString aBuildLog;
1214
1215 if (!aShader->Compile (theGlContext))
1216 {
1217 aShader->FetchInfoLog (theGlContext, aBuildLog);
1218
1219 const TCollection_ExtendedString aMessage = TCollection_ExtendedString ("Error: Failed to compile ") +
1220 (theType == GL_VERTEX_SHADER ? "vertex" : "fragment") + " shader object:\n" + aBuildLog;
1221
1222 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1223 GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, aMessage);
1224
1225 aShader->Release (theGlContext.operator->());
1226
1227#ifdef RAY_TRACE_PRINT_INFO
1228 std::cout << "Shader build log:\n" << aBuildLog << "\n";
1229#endif
1230
1231 return Handle(OpenGl_ShaderObject)();
1232 }
1233 else if (theGlContext->caps->glslWarnings)
1234 {
1235 aShader->FetchInfoLog (theGlContext, aBuildLog);
1236
1237 if (!aBuildLog.IsEmpty() && !aBuildLog.IsEqual ("No errors.\n"))
1238 {
1239 const TCollection_ExtendedString aMessage = TCollection_ExtendedString (theType == GL_VERTEX_SHADER ?
1240 "Vertex" : "Fragment") + " shader was compiled with following warnings:\n" + aBuildLog;
1241
1242 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1243 GL_DEBUG_TYPE_PORTABILITY, 0, GL_DEBUG_SEVERITY_LOW, aMessage);
1244 }
1245
1246#ifdef RAY_TRACE_PRINT_INFO
1247 std::cout << "Shader build log:\n" << aBuildLog << "\n";
1248#endif
1249 }
1250
1251 return aShader;
1252}
1253
1254// =======================================================================
1255// function : initProgram
1256// purpose : Creates GLSL program from the given shader objects
1257// =======================================================================
1258Handle(OpenGl_ShaderProgram) OpenGl_View::initProgram (const Handle(OpenGl_Context)& theGlContext,
1259 const Handle(OpenGl_ShaderObject)& theVertShader,
1260 const Handle(OpenGl_ShaderObject)& theFragShader)
1261{
1262 Handle(OpenGl_ShaderProgram) aProgram = new OpenGl_ShaderProgram;
1263
1264 if (!aProgram->Create (theGlContext))
1265 {
1266 theVertShader->Release (theGlContext.operator->());
1267
1268 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1269 GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, "Failed to create shader program");
1270
1271 return Handle(OpenGl_ShaderProgram)();
1272 }
1273
1274 if (!aProgram->AttachShader (theGlContext, theVertShader)
1275 || !aProgram->AttachShader (theGlContext, theFragShader))
1276 {
1277 theVertShader->Release (theGlContext.operator->());
1278
1279 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1280 GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, "Failed to attach shader objects");
1281
1282 return Handle(OpenGl_ShaderProgram)();
1283 }
1284
1285 aProgram->SetAttributeName (theGlContext, Graphic3d_TOA_POS, "occVertex");
1286
1287 TCollection_AsciiString aLinkLog;
1288
1289 if (!aProgram->Link (theGlContext))
1290 {
1291 aProgram->FetchInfoLog (theGlContext, aLinkLog);
1292
1293 const TCollection_ExtendedString aMessage = TCollection_ExtendedString (
1294 "Failed to link shader program:\n") + aLinkLog;
1295
1296 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1297 GL_DEBUG_TYPE_ERROR, 0, GL_DEBUG_SEVERITY_HIGH, aMessage);
1298
1299 return Handle(OpenGl_ShaderProgram)();
1300 }
1301 else if (theGlContext->caps->glslWarnings)
1302 {
1303 aProgram->FetchInfoLog (theGlContext, aLinkLog);
1304 if (!aLinkLog.IsEmpty() && !aLinkLog.IsEqual ("No errors.\n"))
1305 {
1306 const TCollection_ExtendedString aMessage = TCollection_ExtendedString (
1307 "Shader program was linked with following warnings:\n") + aLinkLog;
1308
1309 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION,
1310 GL_DEBUG_TYPE_PORTABILITY, 0, GL_DEBUG_SEVERITY_LOW, aMessage);
1311 }
1312 }
1313
1314 return aProgram;
1315}
1316
1317// =======================================================================
1318// function : initRaytraceResources
1319// purpose : Initializes OpenGL/GLSL shader programs
1320// =======================================================================
1321Standard_Boolean OpenGl_View::initRaytraceResources (const Handle(OpenGl_Context)& theGlContext)
1322{
1323 if (myRaytraceInitStatus == OpenGl_RT_FAIL)
1324 {
1325 return Standard_False;
1326 }
1327
1328 Standard_Boolean aToRebuildShaders = Standard_False;
1329
1330 if (myRenderParams.RebuildRayTracingShaders) // requires complete re-initialization
1331 {
1332 myRaytraceInitStatus = OpenGl_RT_NONE;
1333 releaseRaytraceResources (theGlContext, Standard_True);
1334 myRenderParams.RebuildRayTracingShaders = Standard_False; // clear rebuilding flag
1335 }
1336
1337 if (myRaytraceInitStatus == OpenGl_RT_INIT)
1338 {
1339 if (!myIsRaytraceDataValid)
1340 {
1341 return Standard_True;
1342 }
1343
1344 const Standard_Integer aRequiredStackSize =
1345 myRaytraceGeometry.TopLevelTreeDepth() + myRaytraceGeometry.BotLevelTreeDepth();
1346
1347 if (myRaytraceParameters.StackSize < aRequiredStackSize)
1348 {
1349 myRaytraceParameters.StackSize = Max (aRequiredStackSize, THE_DEFAULT_STACK_SIZE);
1350
1351 aToRebuildShaders = Standard_True;
1352 }
1353 else
1354 {
1355 if (aRequiredStackSize < myRaytraceParameters.StackSize)
1356 {
1357 if (myRaytraceParameters.StackSize > THE_DEFAULT_STACK_SIZE)
1358 {
1359 myRaytraceParameters.StackSize = Max (aRequiredStackSize, THE_DEFAULT_STACK_SIZE);
1360 aToRebuildShaders = Standard_True;
1361 }
1362 }
1363 }
1364
1365 Standard_Integer aNbTilesX = 8;
1366 Standard_Integer aNbTilesY = 8;
1367
1368 for (Standard_Integer anIdx = 0; aNbTilesX * aNbTilesY < myRenderParams.NbRayTracingTiles; ++anIdx)
1369 {
1370 (anIdx % 2 == 0 ? aNbTilesX : aNbTilesY) <<= 1;
1371 }
1372
1373 if (myRenderParams.RaytracingDepth != myRaytraceParameters.NbBounces
1374 || myRenderParams.IsTransparentShadowEnabled != myRaytraceParameters.TransparentShadows
1375 || myRenderParams.IsGlobalIlluminationEnabled != myRaytraceParameters.GlobalIllumination
1376 || myRenderParams.TwoSidedBsdfModels != myRaytraceParameters.TwoSidedBsdfModels
1377 || myRaytraceGeometry.HasTextures() != myRaytraceParameters.UseBindlessTextures
1378 || aNbTilesX != myRaytraceParameters.NbTilesX
1379 || aNbTilesY != myRaytraceParameters.NbTilesY)
1380 {
1381 myRaytraceParameters.NbBounces = myRenderParams.RaytracingDepth;
1382 myRaytraceParameters.TransparentShadows = myRenderParams.IsTransparentShadowEnabled;
1383 myRaytraceParameters.GlobalIllumination = myRenderParams.IsGlobalIlluminationEnabled;
1384 myRaytraceParameters.TwoSidedBsdfModels = myRenderParams.TwoSidedBsdfModels;
1385 myRaytraceParameters.UseBindlessTextures = myRaytraceGeometry.HasTextures();
1386
1387#ifdef RAY_TRACE_PRINT_INFO
1388 if (aNbTilesX != myRaytraceParameters.NbTilesX
1389 || aNbTilesY != myRaytraceParameters.NbTilesY)
1390 {
1391 std::cout << "Number of tiles X: " << aNbTilesX << "\n";
1392 std::cout << "Number of tiles Y: " << aNbTilesY << "\n";
1393 }
1394#endif
1395
1396 myRaytraceParameters.NbTilesX = aNbTilesX;
1397 myRaytraceParameters.NbTilesY = aNbTilesY;
1398
1399 aToRebuildShaders = Standard_True;
1400 }
1401
1402 if (myRenderParams.AdaptiveScreenSampling != myRaytraceParameters.AdaptiveScreenSampling)
1403 {
1404 myRaytraceParameters.AdaptiveScreenSampling = myRenderParams.AdaptiveScreenSampling;
1405 if (myRenderParams.AdaptiveScreenSampling) // adaptive sampling was requested
1406 {
1407 if (!theGlContext->HasRayTracingAdaptiveSampling())
1408 {
1409 // disable the feature if it is not supported
1410 myRaytraceParameters.AdaptiveScreenSampling = myRenderParams.AdaptiveScreenSampling = Standard_False;
1411 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_PORTABILITY, 0, GL_DEBUG_SEVERITY_LOW,
1412 "Adaptive sampling not supported (OpenGL 4.4 or GL_NV_shader_atomic_float is missing)");
1413 }
1414 }
1415
1416 aToRebuildShaders = Standard_True;
1417 }
1418
1419 const bool toEnableDof = !myCamera->IsOrthographic() && myRaytraceParameters.GlobalIllumination;
1420 if (myRaytraceParameters.DepthOfField != toEnableDof)
1421 {
1422 myRaytraceParameters.DepthOfField = toEnableDof;
1423 aToRebuildShaders = Standard_True;
1424 }
1425
1426 if (myRenderParams.ToneMappingMethod != myRaytraceParameters.ToneMappingMethod)
1427 {
1428 myRaytraceParameters.ToneMappingMethod = myRenderParams.ToneMappingMethod;
1429 aToRebuildShaders = true;
1430 }
1431
1432 if (aToRebuildShaders)
1433 {
1434 // Reject accumulated frames
1435 myAccumFrames = 0;
1436
1437 // Environment map should be updated
1438 myToUpdateEnvironmentMap = Standard_True;
1439
1440 const TCollection_AsciiString aPrefixString = generateShaderPrefix (theGlContext);
1441
1442#ifdef RAY_TRACE_PRINT_INFO
1443 std::cout << "GLSL prefix string:" << std::endl << aPrefixString << std::endl;
1444#endif
1445
1446 myRaytraceShaderSource.SetPrefix (aPrefixString);
1447 myPostFSAAShaderSource.SetPrefix (aPrefixString);
1448 myOutImageShaderSource.SetPrefix (aPrefixString);
1449
1450 if (!myRaytraceShader->LoadSource (theGlContext, myRaytraceShaderSource.Source())
1451 || !myPostFSAAShader->LoadSource (theGlContext, myPostFSAAShaderSource.Source())
1452 || !myOutImageShader->LoadSource (theGlContext, myOutImageShaderSource.Source()))
1453 {
1454 return safeFailBack ("Failed to load source into ray-tracing fragment shaders", theGlContext);
1455 }
1456
1457 TCollection_AsciiString aLog;
1458
1459 if (!myRaytraceShader->Compile (theGlContext)
1460 || !myPostFSAAShader->Compile (theGlContext)
1461 || !myOutImageShader->Compile (theGlContext))
1462 {
1463#ifdef RAY_TRACE_PRINT_INFO
1464 myRaytraceShader->FetchInfoLog (theGlContext, aLog);
1465
1466 if (!aLog.IsEmpty())
1467 {
1468 std::cout << "Failed to compile ray-tracing shader: " << aLog << "\n";
1469 }
1470#endif
1471 return safeFailBack ("Failed to compile ray-tracing fragment shaders", theGlContext);
1472 }
1473
1474 myRaytraceProgram->SetAttributeName (theGlContext, Graphic3d_TOA_POS, "occVertex");
1475 myPostFSAAProgram->SetAttributeName (theGlContext, Graphic3d_TOA_POS, "occVertex");
1476 myOutImageProgram->SetAttributeName (theGlContext, Graphic3d_TOA_POS, "occVertex");
1477
1478 if (!myRaytraceProgram->Link (theGlContext)
1479 || !myPostFSAAProgram->Link (theGlContext)
1480 || !myOutImageProgram->Link (theGlContext))
1481 {
1482#ifdef RAY_TRACE_PRINT_INFO
1483 myRaytraceProgram->FetchInfoLog (theGlContext, aLog);
1484
1485 if (!aLog.IsEmpty())
1486 {
1487 std::cout << "Failed to compile ray-tracing shader: " << aLog << "\n";
1488 }
1489#endif
1490 return safeFailBack ("Failed to initialize vertex attributes for ray-tracing program", theGlContext);
1491 }
1492 }
1493 }
1494
1495 if (myRaytraceInitStatus == OpenGl_RT_NONE)
1496 {
1497 myAccumFrames = 0; // accumulation should be restarted
1498
1499 if (!theGlContext->IsGlGreaterEqual (3, 1))
1500 {
1501 return safeFailBack ("Ray-tracing requires OpenGL 3.1 and higher", theGlContext);
1502 }
1503 else if (!theGlContext->arbTboRGB32)
1504 {
1505 return safeFailBack ("Ray-tracing requires OpenGL 4.0+ or GL_ARB_texture_buffer_object_rgb32 extension", theGlContext);
1506 }
1507 else if (!theGlContext->arbFBOBlit)
1508 {
1509 return safeFailBack ("Ray-tracing requires EXT_framebuffer_blit extension", theGlContext);
1510 }
1511
1512 myRaytraceParameters.NbBounces = myRenderParams.RaytracingDepth;
1513
1514 const TCollection_AsciiString aShaderFolder = Graphic3d_ShaderProgram::ShadersFolder();
1515 if (myIsRaytraceDataValid)
1516 {
1517 myRaytraceParameters.StackSize = Max (THE_DEFAULT_STACK_SIZE,
1518 myRaytraceGeometry.TopLevelTreeDepth() + myRaytraceGeometry.BotLevelTreeDepth());
1519 }
1520
1521 const TCollection_AsciiString aPrefixString = generateShaderPrefix (theGlContext);
1522
1523#ifdef RAY_TRACE_PRINT_INFO
1524 std::cout << "GLSL prefix string:" << std::endl << aPrefixString << std::endl;
1525#endif
1526
1527 ShaderSource aBasicVertShaderSrc;
1528 {
1529 if (!aShaderFolder.IsEmpty())
1530 {
1531 const TCollection_AsciiString aFiles[] = { aShaderFolder + "/RaytraceBase.vs", "" };
1532 if (!aBasicVertShaderSrc.LoadFromFiles (aFiles))
1533 {
1534 return safeFailBack (aBasicVertShaderSrc.ErrorDescription(), theGlContext);
1535 }
1536 }
1537 else
1538 {
1539 const TCollection_AsciiString aSrcShaders[] = { Shaders_RaytraceBase_vs, "" };
1540 aBasicVertShaderSrc.LoadFromStrings (aSrcShaders);
1541 }
1542 }
1543
1544 {
1545 if (!aShaderFolder.IsEmpty())
1546 {
1547 const TCollection_AsciiString aFiles[] = { aShaderFolder + "/RaytraceBase.fs",
1548 aShaderFolder + "/PathtraceBase.fs",
1549 aShaderFolder + "/RaytraceRender.fs",
1550 "" };
1551 if (!myRaytraceShaderSource.LoadFromFiles (aFiles, aPrefixString))
1552 {
1553 return safeFailBack (myRaytraceShaderSource.ErrorDescription(), theGlContext);
1554 }
1555 }
1556 else
1557 {
1558 const TCollection_AsciiString aSrcShaders[] = { Shaders_RaytraceBase_fs,
1559 Shaders_PathtraceBase_fs,
1560 Shaders_RaytraceRender_fs,
1561 "" };
1562 myRaytraceShaderSource.LoadFromStrings (aSrcShaders, aPrefixString);
1563 }
1564
1565 Handle(OpenGl_ShaderObject) aBasicVertShader = initShader (GL_VERTEX_SHADER, aBasicVertShaderSrc, theGlContext);
1566 if (aBasicVertShader.IsNull())
1567 {
1568 return safeFailBack ("Failed to initialize ray-trace vertex shader", theGlContext);
1569 }
1570
1571 myRaytraceShader = initShader (GL_FRAGMENT_SHADER, myRaytraceShaderSource, theGlContext);
1572 if (myRaytraceShader.IsNull())
1573 {
1574 aBasicVertShader->Release (theGlContext.operator->());
1575 return safeFailBack ("Failed to initialize ray-trace fragment shader", theGlContext);
1576 }
1577
1578 myRaytraceProgram = initProgram (theGlContext, aBasicVertShader, myRaytraceShader);
1579 if (myRaytraceProgram.IsNull())
1580 {
1581 return safeFailBack ("Failed to initialize ray-trace shader program", theGlContext);
1582 }
1583 }
1584
1585 {
1586 if (!aShaderFolder.IsEmpty())
1587 {
1588 const TCollection_AsciiString aFiles[] = { aShaderFolder + "/RaytraceBase.fs", aShaderFolder + "/RaytraceSmooth.fs", "" };
1589 if (!myPostFSAAShaderSource.LoadFromFiles (aFiles, aPrefixString))
1590 {
1591 return safeFailBack (myPostFSAAShaderSource.ErrorDescription(), theGlContext);
1592 }
1593 }
1594 else
1595 {
1596 const TCollection_AsciiString aSrcShaders[] = { Shaders_RaytraceBase_fs, Shaders_RaytraceSmooth_fs, "" };
1597 myPostFSAAShaderSource.LoadFromStrings (aSrcShaders, aPrefixString);
1598 }
1599
1600 Handle(OpenGl_ShaderObject) aBasicVertShader = initShader (GL_VERTEX_SHADER, aBasicVertShaderSrc, theGlContext);
1601 if (aBasicVertShader.IsNull())
1602 {
1603 return safeFailBack ("Failed to initialize FSAA vertex shader", theGlContext);
1604 }
1605
1606 myPostFSAAShader = initShader (GL_FRAGMENT_SHADER, myPostFSAAShaderSource, theGlContext);
1607 if (myPostFSAAShader.IsNull())
1608 {
1609 aBasicVertShader->Release (theGlContext.operator->());
1610 return safeFailBack ("Failed to initialize FSAA fragment shader", theGlContext);
1611 }
1612
1613 myPostFSAAProgram = initProgram (theGlContext, aBasicVertShader, myPostFSAAShader);
1614 if (myPostFSAAProgram.IsNull())
1615 {
1616 return safeFailBack ("Failed to initialize FSAA shader program", theGlContext);
1617 }
1618 }
1619
1620 {
1621 if (!aShaderFolder.IsEmpty())
1622 {
1623 const TCollection_AsciiString aFiles[] = { aShaderFolder + "/Display.fs", "" };
1624 if (!myOutImageShaderSource.LoadFromFiles (aFiles, aPrefixString))
1625 {
1626 return safeFailBack (myOutImageShaderSource.ErrorDescription(), theGlContext);
1627 }
1628 }
1629 else
1630 {
1631 const TCollection_AsciiString aSrcShaders[] = { Shaders_Display_fs, "" };
1632 myOutImageShaderSource.LoadFromStrings (aSrcShaders, aPrefixString);
1633 }
1634
1635 Handle(OpenGl_ShaderObject) aBasicVertShader = initShader (GL_VERTEX_SHADER, aBasicVertShaderSrc, theGlContext);
1636 if (aBasicVertShader.IsNull())
1637 {
1638 return safeFailBack ("Failed to set vertex shader source", theGlContext);
1639 }
1640
1641 myOutImageShader = initShader (GL_FRAGMENT_SHADER, myOutImageShaderSource, theGlContext);
1642 if (myOutImageShader.IsNull())
1643 {
1644 aBasicVertShader->Release (theGlContext.operator->());
1645 return safeFailBack ("Failed to set display fragment shader source", theGlContext);
1646 }
1647
1648 myOutImageProgram = initProgram (theGlContext, aBasicVertShader, myOutImageShader);
1649 if (myOutImageProgram.IsNull())
1650 {
1651 return safeFailBack ("Failed to initialize display shader program", theGlContext);
1652 }
1653 }
1654 }
1655
1656 if (myRaytraceInitStatus == OpenGl_RT_NONE || aToRebuildShaders)
1657 {
1658 for (Standard_Integer anIndex = 0; anIndex < 2; ++anIndex)
1659 {
1660 Handle(OpenGl_ShaderProgram)& aShaderProgram =
1661 (anIndex == 0) ? myRaytraceProgram : myPostFSAAProgram;
1662
1663 theGlContext->BindProgram (aShaderProgram);
1664
1665 aShaderProgram->SetSampler (theGlContext,
1666 "uSceneMinPointTexture", OpenGl_RT_SceneMinPointTexture);
1667 aShaderProgram->SetSampler (theGlContext,
1668 "uSceneMaxPointTexture", OpenGl_RT_SceneMaxPointTexture);
1669 aShaderProgram->SetSampler (theGlContext,
1670 "uSceneNodeInfoTexture", OpenGl_RT_SceneNodeInfoTexture);
1671 aShaderProgram->SetSampler (theGlContext,
1672 "uGeometryVertexTexture", OpenGl_RT_GeometryVertexTexture);
1673 aShaderProgram->SetSampler (theGlContext,
1674 "uGeometryNormalTexture", OpenGl_RT_GeometryNormalTexture);
1675 aShaderProgram->SetSampler (theGlContext,
1676 "uGeometryTexCrdTexture", OpenGl_RT_GeometryTexCrdTexture);
1677 aShaderProgram->SetSampler (theGlContext,
1678 "uGeometryTriangTexture", OpenGl_RT_GeometryTriangTexture);
1679 aShaderProgram->SetSampler (theGlContext,
1680 "uSceneTransformTexture", OpenGl_RT_SceneTransformTexture);
1681 aShaderProgram->SetSampler (theGlContext,
1682 "uEnvironmentMapTexture", OpenGl_RT_EnvironmentMapTexture);
1683 aShaderProgram->SetSampler (theGlContext,
1684 "uRaytraceMaterialTexture", OpenGl_RT_RaytraceMaterialTexture);
1685 aShaderProgram->SetSampler (theGlContext,
1686 "uRaytraceLightSrcTexture", OpenGl_RT_RaytraceLightSrcTexture);
1687
1688 if (anIndex == 1)
1689 {
1690 aShaderProgram->SetSampler (theGlContext,
1691 "uFSAAInputTexture", OpenGl_RT_FsaaInputTexture);
1692 }
1693 else
1694 {
1695 aShaderProgram->SetSampler (theGlContext,
1696 "uAccumTexture", OpenGl_RT_PrevAccumTexture);
1697 }
1698
1699 myUniformLocations[anIndex][OpenGl_RT_aPosition] =
1700 aShaderProgram->GetAttributeLocation (theGlContext, "occVertex");
1701
1702 myUniformLocations[anIndex][OpenGl_RT_uOriginLB] =
1703 aShaderProgram->GetUniformLocation (theGlContext, "uOriginLB");
1704 myUniformLocations[anIndex][OpenGl_RT_uOriginRB] =
1705 aShaderProgram->GetUniformLocation (theGlContext, "uOriginRB");
1706 myUniformLocations[anIndex][OpenGl_RT_uOriginLT] =
1707 aShaderProgram->GetUniformLocation (theGlContext, "uOriginLT");
1708 myUniformLocations[anIndex][OpenGl_RT_uOriginRT] =
1709 aShaderProgram->GetUniformLocation (theGlContext, "uOriginRT");
1710 myUniformLocations[anIndex][OpenGl_RT_uDirectLB] =
1711 aShaderProgram->GetUniformLocation (theGlContext, "uDirectLB");
1712 myUniformLocations[anIndex][OpenGl_RT_uDirectRB] =
1713 aShaderProgram->GetUniformLocation (theGlContext, "uDirectRB");
1714 myUniformLocations[anIndex][OpenGl_RT_uDirectLT] =
1715 aShaderProgram->GetUniformLocation (theGlContext, "uDirectLT");
1716 myUniformLocations[anIndex][OpenGl_RT_uDirectRT] =
1717 aShaderProgram->GetUniformLocation (theGlContext, "uDirectRT");
1718 myUniformLocations[anIndex][OpenGl_RT_uViewPrMat] =
1719 aShaderProgram->GetUniformLocation (theGlContext, "uViewMat");
1720 myUniformLocations[anIndex][OpenGl_RT_uUnviewMat] =
1721 aShaderProgram->GetUniformLocation (theGlContext, "uUnviewMat");
1722
1723 myUniformLocations[anIndex][OpenGl_RT_uSceneRad] =
1724 aShaderProgram->GetUniformLocation (theGlContext, "uSceneRadius");
1725 myUniformLocations[anIndex][OpenGl_RT_uSceneEps] =
1726 aShaderProgram->GetUniformLocation (theGlContext, "uSceneEpsilon");
1727 myUniformLocations[anIndex][OpenGl_RT_uLightCount] =
1728 aShaderProgram->GetUniformLocation (theGlContext, "uLightCount");
1729 myUniformLocations[anIndex][OpenGl_RT_uLightAmbnt] =
1730 aShaderProgram->GetUniformLocation (theGlContext, "uGlobalAmbient");
1731
1732 myUniformLocations[anIndex][OpenGl_RT_uOffsetX] =
1733 aShaderProgram->GetUniformLocation (theGlContext, "uOffsetX");
1734 myUniformLocations[anIndex][OpenGl_RT_uOffsetY] =
1735 aShaderProgram->GetUniformLocation (theGlContext, "uOffsetY");
1736 myUniformLocations[anIndex][OpenGl_RT_uSamples] =
1737 aShaderProgram->GetUniformLocation (theGlContext, "uSamples");
1738
1739 myUniformLocations[anIndex][OpenGl_RT_uTexSamplersArray] =
1740 aShaderProgram->GetUniformLocation (theGlContext, "uTextureSamplers");
1741
1742 myUniformLocations[anIndex][OpenGl_RT_uShadowsEnabled] =
1743 aShaderProgram->GetUniformLocation (theGlContext, "uShadowsEnabled");
1744 myUniformLocations[anIndex][OpenGl_RT_uReflectEnabled] =
1745 aShaderProgram->GetUniformLocation (theGlContext, "uReflectEnabled");
1746 myUniformLocations[anIndex][OpenGl_RT_uSphereMapEnabled] =
1747 aShaderProgram->GetUniformLocation (theGlContext, "uSphereMapEnabled");
1748 myUniformLocations[anIndex][OpenGl_RT_uSphereMapForBack] =
1749 aShaderProgram->GetUniformLocation (theGlContext, "uSphereMapForBack");
1750 myUniformLocations[anIndex][OpenGl_RT_uBlockedRngEnabled] =
1751 aShaderProgram->GetUniformLocation (theGlContext, "uBlockedRngEnabled");
1752
1753 myUniformLocations[anIndex][OpenGl_RT_uWinSizeX] =
1754 aShaderProgram->GetUniformLocation (theGlContext, "uWinSizeX");
1755 myUniformLocations[anIndex][OpenGl_RT_uWinSizeY] =
1756 aShaderProgram->GetUniformLocation (theGlContext, "uWinSizeY");
1757
1758 myUniformLocations[anIndex][OpenGl_RT_uAccumSamples] =
1759 aShaderProgram->GetUniformLocation (theGlContext, "uAccumSamples");
1760 myUniformLocations[anIndex][OpenGl_RT_uFrameRndSeed] =
1761 aShaderProgram->GetUniformLocation (theGlContext, "uFrameRndSeed");
1762
1763 myUniformLocations[anIndex][OpenGl_RT_uRenderImage] =
1764 aShaderProgram->GetUniformLocation (theGlContext, "uRenderImage");
1765 myUniformLocations[anIndex][OpenGl_RT_uOffsetImage] =
1766 aShaderProgram->GetUniformLocation (theGlContext, "uOffsetImage");
1767
1768 myUniformLocations[anIndex][OpenGl_RT_uBackColorTop] =
1769 aShaderProgram->GetUniformLocation (theGlContext, "uBackColorTop");
1770 myUniformLocations[anIndex][OpenGl_RT_uBackColorBot] =
1771 aShaderProgram->GetUniformLocation (theGlContext, "uBackColorBot");
1772
1773 myUniformLocations[anIndex][OpenGl_RT_uMaxRadiance] =
1774 aShaderProgram->GetUniformLocation (theGlContext, "uMaxRadiance");
1775 }
1776
1777 theGlContext->BindProgram (myOutImageProgram);
1778
1779 myOutImageProgram->SetSampler (theGlContext,
1780 "uInputTexture", OpenGl_RT_PrevAccumTexture);
1781
1782 myOutImageProgram->SetSampler (theGlContext,
1783 "uDepthTexture", OpenGl_RT_RaytraceDepthTexture);
1784
1785 theGlContext->BindProgram (NULL);
1786 }
1787
1788 if (myRaytraceInitStatus != OpenGl_RT_NONE)
1789 {
1790 return myRaytraceInitStatus == OpenGl_RT_INIT;
1791 }
1792
1793 const GLfloat aVertices[] = { -1.f, -1.f, 0.f,
1794 -1.f, 1.f, 0.f,
1795 1.f, 1.f, 0.f,
1796 1.f, 1.f, 0.f,
1797 1.f, -1.f, 0.f,
1798 -1.f, -1.f, 0.f };
1799
1800 myRaytraceScreenQuad.Init (theGlContext, 3, 6, aVertices);
1801
1802 myRaytraceInitStatus = OpenGl_RT_INIT; // initialized in normal way
1803
1804 return Standard_True;
1805}
1806
1807// =======================================================================
1808// function : nullifyResource
1809// purpose : Releases OpenGL resource
1810// =======================================================================
1811template <class T>
1812inline void nullifyResource (const Handle(OpenGl_Context)& theGlContext, Handle(T)& theResource)
1813{
1814 if (!theResource.IsNull())
1815 {
1816 theResource->Release (theGlContext.operator->());
1817 theResource.Nullify();
1818 }
1819}
1820
1821// =======================================================================
1822// function : releaseRaytraceResources
1823// purpose : Releases OpenGL/GLSL shader programs
1824// =======================================================================
1825void OpenGl_View::releaseRaytraceResources (const Handle(OpenGl_Context)& theGlContext, const Standard_Boolean theToRebuild)
1826{
1827 // release shader resources
1828 nullifyResource (theGlContext, myRaytraceShader);
1829 nullifyResource (theGlContext, myPostFSAAShader);
1830
1831 nullifyResource (theGlContext, myRaytraceProgram);
1832 nullifyResource (theGlContext, myPostFSAAProgram);
1833 nullifyResource (theGlContext, myOutImageProgram);
1834
1835 if (!theToRebuild) // complete release
1836 {
1837 myRaytraceFBO1[0]->Release (theGlContext.operator->());
1838 myRaytraceFBO1[1]->Release (theGlContext.operator->());
1839 myRaytraceFBO2[0]->Release (theGlContext.operator->());
1840 myRaytraceFBO2[1]->Release (theGlContext.operator->());
1841
1842 nullifyResource (theGlContext, myRaytraceOutputTexture[0]);
1843 nullifyResource (theGlContext, myRaytraceOutputTexture[1]);
1844
1845 nullifyResource (theGlContext, myRaytraceTileOffsetsTexture[0]);
1846 nullifyResource (theGlContext, myRaytraceTileOffsetsTexture[1]);
1847 nullifyResource (theGlContext, myRaytraceVisualErrorTexture[0]);
1848 nullifyResource (theGlContext, myRaytraceVisualErrorTexture[1]);
1849
1850 nullifyResource (theGlContext, mySceneNodeInfoTexture);
1851 nullifyResource (theGlContext, mySceneMinPointTexture);
1852 nullifyResource (theGlContext, mySceneMaxPointTexture);
1853
1854 nullifyResource (theGlContext, myGeometryVertexTexture);
1855 nullifyResource (theGlContext, myGeometryNormalTexture);
1856 nullifyResource (theGlContext, myGeometryTexCrdTexture);
1857 nullifyResource (theGlContext, myGeometryTriangTexture);
1858 nullifyResource (theGlContext, mySceneTransformTexture);
1859
1860 nullifyResource (theGlContext, myRaytraceLightSrcTexture);
1861 nullifyResource (theGlContext, myRaytraceMaterialTexture);
1862
1863 myRaytraceGeometry.ReleaseResources (theGlContext);
1864
1865 if (myRaytraceScreenQuad.IsValid ())
1866 {
1867 myRaytraceScreenQuad.Release (theGlContext.operator->());
1868 }
1869 }
1870}
1871
1872// =======================================================================
1873// function : updateRaytraceBuffers
1874// purpose : Updates auxiliary OpenGL frame buffers.
1875// =======================================================================
1876Standard_Boolean OpenGl_View::updateRaytraceBuffers (const Standard_Integer theSizeX,
1877 const Standard_Integer theSizeY,
1878 const Handle(OpenGl_Context)& theGlContext)
1879{
1880 // Auxiliary buffers are not used
1881 if (!myRaytraceParameters.GlobalIllumination && !myRenderParams.IsAntialiasingEnabled)
1882 {
1883 myRaytraceFBO1[0]->Release (theGlContext.operator->());
1884 myRaytraceFBO2[0]->Release (theGlContext.operator->());
1885 myRaytraceFBO1[1]->Release (theGlContext.operator->());
1886 myRaytraceFBO2[1]->Release (theGlContext.operator->());
1887
1888 return Standard_True;
1889 }
1890
1891 if (myRaytraceParameters.AdaptiveScreenSampling)
1892 {
1893 const Standard_Integer aSizeX = std::max (myRaytraceParameters.NbTilesX * 64, theSizeX);
1894 const Standard_Integer aSizeY = std::max (myRaytraceParameters.NbTilesY * 64, theSizeY);
1895
1896 myRaytraceFBO1[0]->InitLazy (theGlContext, aSizeX, aSizeY, GL_RGBA32F, myFboDepthFormat);
1897 myRaytraceFBO2[0]->InitLazy (theGlContext, aSizeX, aSizeY, GL_RGBA32F, myFboDepthFormat);
1898
1899 if (myRaytraceFBO1[1]->IsValid()) // second FBO not needed
1900 {
1901 myRaytraceFBO1[1]->Release (theGlContext.operator->());
1902 myRaytraceFBO2[1]->Release (theGlContext.operator->());
1903 }
1904 }
1905 else // non-adaptive mode
1906 {
1907 if (myRaytraceFBO1[0]->GetSizeX() != theSizeX
1908 || myRaytraceFBO1[0]->GetSizeY() != theSizeY)
1909 {
1910 myAccumFrames = 0; // accumulation should be restarted
1911 }
1912
1913 myRaytraceFBO1[0]->InitLazy (theGlContext, theSizeX, theSizeY, GL_RGBA32F, myFboDepthFormat);
1914 myRaytraceFBO2[0]->InitLazy (theGlContext, theSizeX, theSizeY, GL_RGBA32F, myFboDepthFormat);
1915
1916 // Init second set of buffers for stereographic rendering
1917 if (myCamera->ProjectionType() == Graphic3d_Camera::Projection_Stereo)
1918 {
1919 myRaytraceFBO1[1]->InitLazy (theGlContext, theSizeX, theSizeY, GL_RGBA32F, myFboDepthFormat);
1920 myRaytraceFBO2[1]->InitLazy (theGlContext, theSizeX, theSizeY, GL_RGBA32F, myFboDepthFormat);
1921 }
1922 else if (myRaytraceFBO1[1]->IsValid()) // second FBO not needed
1923 {
1924 myRaytraceFBO1[1]->Release (theGlContext.operator->());
1925 myRaytraceFBO2[1]->Release (theGlContext.operator->());
1926 }
1927 }
1928
1929 myTileSampler.SetSize (theSizeX, theSizeY);
1930
1931 if (myRaytraceTileOffsetsTexture[0].IsNull()
1932 || myRaytraceTileOffsetsTexture[1].IsNull())
1933 {
1934 myRaytraceOutputTexture[0] = new OpenGl_Texture();
1935 myRaytraceOutputTexture[1] = new OpenGl_Texture();
1936
1937 myRaytraceTileOffsetsTexture[0] = new OpenGl_Texture();
1938 myRaytraceTileOffsetsTexture[1] = new OpenGl_Texture();
1939 myRaytraceVisualErrorTexture[0] = new OpenGl_Texture();
1940 myRaytraceVisualErrorTexture[1] = new OpenGl_Texture();
1941 }
1942
1943 if (myRaytraceOutputTexture[0]->SizeX() / 3 != theSizeX
1944 || myRaytraceOutputTexture[0]->SizeY() / 2 != theSizeY)
1945 {
1946 myAccumFrames = 0;
1947
1948 // Due to limitations of OpenGL image load-store extension
1949 // atomic operations are supported only for single-channel
1950 // images, so we define GL_R32F image. It is used as array
1951 // of 6D floating point vectors:
1952 // 0 - R color channel
1953 // 1 - G color channel
1954 // 2 - B color channel
1955 // 3 - hit time transformed into OpenGL NDC space
1956 // 4 - luminance accumulated for odd samples only
1957 myRaytraceOutputTexture[0]->InitRectangle (theGlContext,
1958 theSizeX * 3, theSizeY * 2, OpenGl_TextureFormat::Create<GLfloat, 1>());
1959
1960 // workaround for some NVIDIA drivers
1961 myRaytraceVisualErrorTexture[0]->Release (theGlContext.operator->());
1962 myRaytraceTileOffsetsTexture[0]->Release (theGlContext.operator->());
1963
1964 myRaytraceVisualErrorTexture[0]->Init (theGlContext,
1965 GL_R32I, GL_RED_INTEGER, GL_INT, myTileSampler.NbTilesX(), myTileSampler.NbTilesY(), Graphic3d_TOT_2D);
1966
1967 myRaytraceTileOffsetsTexture[0]->Init (theGlContext,
1968 GL_RG32I, GL_RG_INTEGER, GL_INT, myTileSampler.NbTilesX(), myTileSampler.NbTilesY(), Graphic3d_TOT_2D);
1969 }
1970
1971 if (myCamera->ProjectionType() == Graphic3d_Camera::Projection_Stereo)
1972 {
1973 if (myRaytraceOutputTexture[1]->SizeX() / 3 != theSizeX
1974 || myRaytraceOutputTexture[1]->SizeY() / 2 != theSizeY)
1975 {
1976 myRaytraceOutputTexture[1]->InitRectangle (theGlContext,
1977 theSizeX * 3, theSizeY * 2, OpenGl_TextureFormat::Create<GLfloat, 1>());
1978
1979 myRaytraceVisualErrorTexture[1]->Release (theGlContext.operator->());
1980 myRaytraceTileOffsetsTexture[1]->Release (theGlContext.operator->());
1981
1982 myRaytraceVisualErrorTexture[1]->Init (theGlContext,
1983 GL_R32I, GL_RED_INTEGER, GL_INT, myTileSampler.NbTilesX(), myTileSampler.NbTilesY(), Graphic3d_TOT_2D);
1984
1985 myRaytraceTileOffsetsTexture[1]->Init (theGlContext,
1986 GL_RG32I, GL_RG_INTEGER, GL_INT, myTileSampler.NbTilesX(), myTileSampler.NbTilesY(), Graphic3d_TOT_2D);
1987 }
1988 }
1989 else
1990 {
1991 myRaytraceOutputTexture[1]->Release (theGlContext.operator->());
1992 }
1993
1994 return Standard_True;
1995}
1996
1997// =======================================================================
1998// function : updateCamera
1999// purpose : Generates viewing rays for corners of screen quad
2000// =======================================================================
2001void OpenGl_View::updateCamera (const OpenGl_Mat4& theOrientation,
2002 const OpenGl_Mat4& theViewMapping,
2003 OpenGl_Vec3* theOrigins,
2004 OpenGl_Vec3* theDirects,
2005 OpenGl_Mat4& theViewPr,
2006 OpenGl_Mat4& theUnview)
2007{
2008 // compute view-projection matrix
2009 theViewPr = theViewMapping * theOrientation;
2010
2011 // compute inverse view-projection matrix
2012 theViewPr.Inverted (theUnview);
2013
2014 Standard_Integer aOriginIndex = 0;
2015 Standard_Integer aDirectIndex = 0;
2016
2017 for (Standard_Integer aY = -1; aY <= 1; aY += 2)
2018 {
2019 for (Standard_Integer aX = -1; aX <= 1; aX += 2)
2020 {
2021 OpenGl_Vec4 aOrigin (GLfloat(aX),
2022 GLfloat(aY),
2023 -1.0f,
2024 1.0f);
2025
2026 aOrigin = theUnview * aOrigin;
2027
2028 aOrigin.x() = aOrigin.x() / aOrigin.w();
2029 aOrigin.y() = aOrigin.y() / aOrigin.w();
2030 aOrigin.z() = aOrigin.z() / aOrigin.w();
2031
2032 OpenGl_Vec4 aDirect (GLfloat(aX),
2033 GLfloat(aY),
2034 1.0f,
2035 1.0f);
2036
2037 aDirect = theUnview * aDirect;
2038
2039 aDirect.x() = aDirect.x() / aDirect.w();
2040 aDirect.y() = aDirect.y() / aDirect.w();
2041 aDirect.z() = aDirect.z() / aDirect.w();
2042
2043 aDirect = aDirect - aOrigin;
2044
2045 theOrigins[aOriginIndex++] = OpenGl_Vec3 (static_cast<GLfloat> (aOrigin.x()),
2046 static_cast<GLfloat> (aOrigin.y()),
2047 static_cast<GLfloat> (aOrigin.z()));
2048
2049 theDirects[aDirectIndex++] = OpenGl_Vec3 (static_cast<GLfloat> (aDirect.x()),
2050 static_cast<GLfloat> (aDirect.y()),
2051 static_cast<GLfloat> (aDirect.z()));
2052 }
2053 }
2054}
2055
2056// =======================================================================
2057// function : updatePerspCameraPT
2058// purpose : Generates viewing rays (path tracing, perspective camera)
2059// =======================================================================
2060void OpenGl_View::updatePerspCameraPT (const OpenGl_Mat4& theOrientation,
2061 const OpenGl_Mat4& theViewMapping,
2062 Graphic3d_Camera::Projection theProjection,
2063 OpenGl_Mat4& theViewPr,
2064 OpenGl_Mat4& theUnview,
2065 const int theWinSizeX,
2066 const int theWinSizeY)
2067{
2068 // compute view-projection matrix
2069 theViewPr = theViewMapping * theOrientation;
2070
2071 // compute inverse view-projection matrix
2072 theViewPr.Inverted(theUnview);
2073
2074 // get camera stereo params
2075 float anIOD = myCamera->GetIODType() == Graphic3d_Camera::IODType_Relative
2076 ? static_cast<float> (myCamera->IOD() * myCamera->Distance())
2077 : static_cast<float> (myCamera->IOD());
2078
2079 float aZFocus = myCamera->ZFocusType() == Graphic3d_Camera::FocusType_Relative
2080 ? static_cast<float> (myCamera->ZFocus() * myCamera->Distance())
2081 : static_cast<float> (myCamera->ZFocus());
2082
2083 // get camera view vectors
2084 const gp_Pnt anOrig = myCamera->Eye();
2085
2086 myEyeOrig = OpenGl_Vec3 (static_cast<float> (anOrig.X()),
2087 static_cast<float> (anOrig.Y()),
2088 static_cast<float> (anOrig.Z()));
2089
2090 const gp_Dir aView = myCamera->Direction();
2091
2092 OpenGl_Vec3 anEyeViewMono = OpenGl_Vec3 (static_cast<float> (aView.X()),
2093 static_cast<float> (aView.Y()),
2094 static_cast<float> (aView.Z()));
2095
2096 const gp_Dir anUp = myCamera->Up();
2097
2098 myEyeVert = OpenGl_Vec3 (static_cast<float> (anUp.X()),
2099 static_cast<float> (anUp.Y()),
2100 static_cast<float> (anUp.Z()));
2101
2102 myEyeSide = OpenGl_Vec3::Cross (anEyeViewMono, myEyeVert);
2103
2104 const double aScaleY = tan (myCamera->FOVy() / 360 * M_PI);
2105 const double aScaleX = theWinSizeX * aScaleY / theWinSizeY;
2106
2107 myEyeSize = OpenGl_Vec2 (static_cast<float> (aScaleX),
2108 static_cast<float> (aScaleY));
2109
2110 if (theProjection == Graphic3d_Camera::Projection_Perspective)
2111 {
2112 myEyeView = anEyeViewMono;
2113 }
2114 else // stereo camera
2115 {
2116 // compute z-focus point
2117 OpenGl_Vec3 aZFocusPoint = myEyeOrig + anEyeViewMono * aZFocus;
2118
2119 // compute stereo camera shift
2120 float aDx = theProjection == Graphic3d_Camera::Projection_MonoRightEye ? 0.5f * anIOD : -0.5f * anIOD;
2121 myEyeOrig += myEyeSide.Normalized() * aDx;
2122
2123 // estimate new camera direction vector and correct its length
2124 myEyeView = (aZFocusPoint - myEyeOrig).Normalized();
2125 myEyeView *= 1.f / anEyeViewMono.Dot (myEyeView);
2126 }
2127}
2128
2129// =======================================================================
2130// function : uploadRaytraceData
2131// purpose : Uploads ray-trace data to the GPU
2132// =======================================================================
2133Standard_Boolean OpenGl_View::uploadRaytraceData (const Handle(OpenGl_Context)& theGlContext)
2134{
2135 if (!theGlContext->IsGlGreaterEqual (3, 1))
2136 {
2137#ifdef RAY_TRACE_PRINT_INFO
2138 std::cout << "Error: OpenGL version is less than 3.1" << std::endl;
2139#endif
2140 return Standard_False;
2141 }
2142
2143 myAccumFrames = 0; // accumulation should be restarted
2144
2145 /////////////////////////////////////////////////////////////////////////////
2146 // Prepare OpenGL textures
2147
2148 if (theGlContext->arbTexBindless != NULL)
2149 {
2150 // If OpenGL driver supports bindless textures we need
2151 // to get unique 64- bit handles for using on the GPU
2152 if (!myRaytraceGeometry.UpdateTextureHandles (theGlContext))
2153 {
2154#ifdef RAY_TRACE_PRINT_INFO
2155 std::cout << "Error: Failed to get OpenGL texture handles" << std::endl;
2156#endif
2157 return Standard_False;
2158 }
2159 }
2160
2161 /////////////////////////////////////////////////////////////////////////////
2162 // Create OpenGL BVH buffers
2163
2164 if (mySceneNodeInfoTexture.IsNull()) // create scene BVH buffers
2165 {
2166 mySceneNodeInfoTexture = new OpenGl_TextureBufferArb;
2167 mySceneMinPointTexture = new OpenGl_TextureBufferArb;
2168 mySceneMaxPointTexture = new OpenGl_TextureBufferArb;
2169 mySceneTransformTexture = new OpenGl_TextureBufferArb;
2170
2171 if (!mySceneNodeInfoTexture->Create (theGlContext)
2172 || !mySceneMinPointTexture->Create (theGlContext)
2173 || !mySceneMaxPointTexture->Create (theGlContext)
2174 || !mySceneTransformTexture->Create (theGlContext))
2175 {
2176#ifdef RAY_TRACE_PRINT_INFO
2177 std::cout << "Error: Failed to create scene BVH buffers" << std::endl;
2178#endif
2179 return Standard_False;
2180 }
2181 }
2182
2183 if (myGeometryVertexTexture.IsNull()) // create geometry buffers
2184 {
2185 myGeometryVertexTexture = new OpenGl_TextureBufferArb;
2186 myGeometryNormalTexture = new OpenGl_TextureBufferArb;
2187 myGeometryTexCrdTexture = new OpenGl_TextureBufferArb;
2188 myGeometryTriangTexture = new OpenGl_TextureBufferArb;
2189
2190 if (!myGeometryVertexTexture->Create (theGlContext)
2191 || !myGeometryNormalTexture->Create (theGlContext)
2192 || !myGeometryTexCrdTexture->Create (theGlContext)
2193 || !myGeometryTriangTexture->Create (theGlContext))
2194 {
2195#ifdef RAY_TRACE_PRINT_INFO
2196 std::cout << "Error: Failed to create buffers for triangulation data" << std::endl;
2197#endif
2198 return Standard_False;
2199 }
2200 }
2201
2202 if (myRaytraceMaterialTexture.IsNull()) // create material buffer
2203 {
2204 myRaytraceMaterialTexture = new OpenGl_TextureBufferArb;
2205
2206 if (!myRaytraceMaterialTexture->Create (theGlContext))
2207 {
2208#ifdef RAY_TRACE_PRINT_INFO
2209 std::cout << "Error: Failed to create buffers for material data" << std::endl;
2210#endif
2211 return Standard_False;
2212 }
2213 }
2214
2215 /////////////////////////////////////////////////////////////////////////////
2216 // Write transform buffer
2217
2218 BVH_Mat4f* aNodeTransforms = new BVH_Mat4f[myRaytraceGeometry.Size()];
2219
2220 bool aResult = true;
2221
2222 for (Standard_Integer anElemIndex = 0; anElemIndex < myRaytraceGeometry.Size(); ++anElemIndex)
2223 {
2224 OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
2225 myRaytraceGeometry.Objects().ChangeValue (anElemIndex).operator->());
2226
2227 const BVH_Transform<Standard_ShortReal, 4>* aTransform = dynamic_cast<const BVH_Transform<Standard_ShortReal, 4>* > (aTriangleSet->Properties().get());
2228 Standard_ASSERT_RETURN (aTransform != NULL,
2229 "OpenGl_TriangleSet does not contain transform", Standard_False);
2230
2231 aNodeTransforms[anElemIndex] = aTransform->Inversed();
2232 }
2233
2234 aResult &= mySceneTransformTexture->Init (theGlContext, 4,
2235 myRaytraceGeometry.Size() * 4, reinterpret_cast<const GLfloat*> (aNodeTransforms));
2236
2237 delete [] aNodeTransforms;
2238
2239 /////////////////////////////////////////////////////////////////////////////
2240 // Write geometry and bottom-level BVH buffers
2241
2242 Standard_Size aTotalVerticesNb = 0;
2243 Standard_Size aTotalElementsNb = 0;
2244 Standard_Size aTotalBVHNodesNb = 0;
2245
2246 for (Standard_Integer anElemIndex = 0; anElemIndex < myRaytraceGeometry.Size(); ++anElemIndex)
2247 {
2248 OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
2249 myRaytraceGeometry.Objects().ChangeValue (anElemIndex).operator->());
2250
2251 Standard_ASSERT_RETURN (aTriangleSet != NULL,
2252 "Error: Failed to get triangulation of OpenGL element", Standard_False);
2253
2254 aTotalVerticesNb += aTriangleSet->Vertices.size();
2255 aTotalElementsNb += aTriangleSet->Elements.size();
2256
2257 Standard_ASSERT_RETURN (!aTriangleSet->QuadBVH().IsNull(),
2258 "Error: Failed to get bottom-level BVH of OpenGL element", Standard_False);
2259
2260 aTotalBVHNodesNb += aTriangleSet->QuadBVH()->NodeInfoBuffer().size();
2261 }
2262
2263 aTotalBVHNodesNb += myRaytraceGeometry.QuadBVH()->NodeInfoBuffer().size();
2264
2265 if (aTotalBVHNodesNb != 0)
2266 {
2267 aResult &= mySceneNodeInfoTexture->Init (
2268 theGlContext, 4, GLsizei (aTotalBVHNodesNb), static_cast<const GLuint*> (NULL));
2269 aResult &= mySceneMinPointTexture->Init (
2270 theGlContext, 3, GLsizei (aTotalBVHNodesNb), static_cast<const GLfloat*> (NULL));
2271 aResult &= mySceneMaxPointTexture->Init (
2272 theGlContext, 3, GLsizei (aTotalBVHNodesNb), static_cast<const GLfloat*> (NULL));
2273 }
2274
2275 if (!aResult)
2276 {
2277#ifdef RAY_TRACE_PRINT_INFO
2278 std::cout << "Error: Failed to upload buffers for bottom-level scene BVH" << std::endl;
2279#endif
2280 return Standard_False;
2281 }
2282
2283 if (aTotalElementsNb != 0)
2284 {
2285 aResult &= myGeometryTriangTexture->Init (
2286 theGlContext, 4, GLsizei (aTotalElementsNb), static_cast<const GLuint*> (NULL));
2287 }
2288
2289 if (aTotalVerticesNb != 0)
2290 {
2291 aResult &= myGeometryVertexTexture->Init (
2292 theGlContext, 3, GLsizei (aTotalVerticesNb), static_cast<const GLfloat*> (NULL));
2293 aResult &= myGeometryNormalTexture->Init (
2294 theGlContext, 3, GLsizei (aTotalVerticesNb), static_cast<const GLfloat*> (NULL));
2295 aResult &= myGeometryTexCrdTexture->Init (
2296 theGlContext, 2, GLsizei (aTotalVerticesNb), static_cast<const GLfloat*> (NULL));
2297 }
2298
2299 if (!aResult)
2300 {
2301#ifdef RAY_TRACE_PRINT_INFO
2302 std::cout << "Error: Failed to upload buffers for scene geometry" << std::endl;
2303#endif
2304 return Standard_False;
2305 }
2306
2307 const QuadBvhHandle& aBVH = myRaytraceGeometry.QuadBVH();
2308
2309 if (aBVH->Length() > 0)
2310 {
2311 aResult &= mySceneNodeInfoTexture->SubData (theGlContext, 0, aBVH->Length(),
2312 reinterpret_cast<const GLuint*> (&aBVH->NodeInfoBuffer().front()));
2313 aResult &= mySceneMinPointTexture->SubData (theGlContext, 0, aBVH->Length(),
2314 reinterpret_cast<const GLfloat*> (&aBVH->MinPointBuffer().front()));
2315 aResult &= mySceneMaxPointTexture->SubData (theGlContext, 0, aBVH->Length(),
2316 reinterpret_cast<const GLfloat*> (&aBVH->MaxPointBuffer().front()));
2317 }
2318
2319 for (Standard_Integer aNodeIdx = 0; aNodeIdx < aBVH->Length(); ++aNodeIdx)
2320 {
2321 if (!aBVH->IsOuter (aNodeIdx))
2322 continue;
2323
2324 OpenGl_TriangleSet* aTriangleSet = myRaytraceGeometry.TriangleSet (aNodeIdx);
2325
2326 Standard_ASSERT_RETURN (aTriangleSet != NULL,
2327 "Error: Failed to get triangulation of OpenGL element", Standard_False);
2328
2329 Standard_Integer aBVHOffset = myRaytraceGeometry.AccelerationOffset (aNodeIdx);
2330
2331 Standard_ASSERT_RETURN (aBVHOffset != OpenGl_RaytraceGeometry::INVALID_OFFSET,
2332 "Error: Failed to get offset for bottom-level BVH", Standard_False);
2333
2334 const Standard_Integer aBvhBuffersSize = aTriangleSet->QuadBVH()->Length();
2335
2336 if (aBvhBuffersSize != 0)
2337 {
2338 aResult &= mySceneNodeInfoTexture->SubData (theGlContext, aBVHOffset, aBvhBuffersSize,
2339 reinterpret_cast<const GLuint*> (&aTriangleSet->QuadBVH()->NodeInfoBuffer().front()));
2340 aResult &= mySceneMinPointTexture->SubData (theGlContext, aBVHOffset, aBvhBuffersSize,
2341 reinterpret_cast<const GLfloat*> (&aTriangleSet->QuadBVH()->MinPointBuffer().front()));
2342 aResult &= mySceneMaxPointTexture->SubData (theGlContext, aBVHOffset, aBvhBuffersSize,
2343 reinterpret_cast<const GLfloat*> (&aTriangleSet->QuadBVH()->MaxPointBuffer().front()));
2344
2345 if (!aResult)
2346 {
2347#ifdef RAY_TRACE_PRINT_INFO
2348 std::cout << "Error: Failed to upload buffers for bottom-level scene BVHs" << std::endl;
2349#endif
2350 return Standard_False;
2351 }
2352 }
2353
2354 const Standard_Integer aVerticesOffset = myRaytraceGeometry.VerticesOffset (aNodeIdx);
2355
2356 Standard_ASSERT_RETURN (aVerticesOffset != OpenGl_RaytraceGeometry::INVALID_OFFSET,
2357 "Error: Failed to get offset for triangulation vertices of OpenGL element", Standard_False);
2358
2359 if (!aTriangleSet->Vertices.empty())
2360 {
2361 aResult &= myGeometryNormalTexture->SubData (theGlContext, aVerticesOffset,
2362 GLsizei (aTriangleSet->Normals.size()), reinterpret_cast<const GLfloat*> (&aTriangleSet->Normals.front()));
2363 aResult &= myGeometryTexCrdTexture->SubData (theGlContext, aVerticesOffset,
2364 GLsizei (aTriangleSet->TexCrds.size()), reinterpret_cast<const GLfloat*> (&aTriangleSet->TexCrds.front()));
2365 aResult &= myGeometryVertexTexture->SubData (theGlContext, aVerticesOffset,
2366 GLsizei (aTriangleSet->Vertices.size()), reinterpret_cast<const GLfloat*> (&aTriangleSet->Vertices.front()));
2367 }
2368
2369 const Standard_Integer anElementsOffset = myRaytraceGeometry.ElementsOffset (aNodeIdx);
2370
2371 Standard_ASSERT_RETURN (anElementsOffset != OpenGl_RaytraceGeometry::INVALID_OFFSET,
2372 "Error: Failed to get offset for triangulation elements of OpenGL element", Standard_False);
2373
2374 if (!aTriangleSet->Elements.empty())
2375 {
2376 aResult &= myGeometryTriangTexture->SubData (theGlContext, anElementsOffset, GLsizei (aTriangleSet->Elements.size()),
2377 reinterpret_cast<const GLuint*> (&aTriangleSet->Elements.front()));
2378 }
2379
2380 if (!aResult)
2381 {
2382#ifdef RAY_TRACE_PRINT_INFO
2383 std::cout << "Error: Failed to upload triangulation buffers for OpenGL element" << std::endl;
2384#endif
2385 return Standard_False;
2386 }
2387 }
2388
2389 /////////////////////////////////////////////////////////////////////////////
2390 // Write material buffer
2391
2392 if (myRaytraceGeometry.Materials.size() != 0)
2393 {
2394 aResult &= myRaytraceMaterialTexture->Init (theGlContext, 4,
2395 GLsizei (myRaytraceGeometry.Materials.size() * 19), myRaytraceGeometry.Materials.front().Packed());
2396
2397 if (!aResult)
2398 {
2399#ifdef RAY_TRACE_PRINT_INFO
2400 std::cout << "Error: Failed to upload material buffer" << std::endl;
2401#endif
2402 return Standard_False;
2403 }
2404 }
2405
2406 myIsRaytraceDataValid = myRaytraceGeometry.Objects().Size() != 0;
2407
2408#ifdef RAY_TRACE_PRINT_INFO
2409
2410 Standard_ShortReal aMemTrgUsed = 0.f;
2411 Standard_ShortReal aMemBvhUsed = 0.f;
2412
2413 for (Standard_Integer anElemIdx = 0; anElemIdx < myRaytraceGeometry.Size(); ++anElemIdx)
2414 {
2415 OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (myRaytraceGeometry.Objects()(anElemIdx).get());
2416
2417 aMemTrgUsed += static_cast<Standard_ShortReal> (
2418 aTriangleSet->Vertices.size() * sizeof (BVH_Vec3f));
2419 aMemTrgUsed += static_cast<Standard_ShortReal> (
2420 aTriangleSet->Normals.size() * sizeof (BVH_Vec3f));
2421 aMemTrgUsed += static_cast<Standard_ShortReal> (
2422 aTriangleSet->TexCrds.size() * sizeof (BVH_Vec2f));
2423 aMemTrgUsed += static_cast<Standard_ShortReal> (
2424 aTriangleSet->Elements.size() * sizeof (BVH_Vec4i));
2425
2426 aMemBvhUsed += static_cast<Standard_ShortReal> (
2427 aTriangleSet->QuadBVH()->NodeInfoBuffer().size() * sizeof (BVH_Vec4i));
2428 aMemBvhUsed += static_cast<Standard_ShortReal> (
2429 aTriangleSet->QuadBVH()->MinPointBuffer().size() * sizeof (BVH_Vec3f));
2430 aMemBvhUsed += static_cast<Standard_ShortReal> (
2431 aTriangleSet->QuadBVH()->MaxPointBuffer().size() * sizeof (BVH_Vec3f));
2432 }
2433
2434 aMemBvhUsed += static_cast<Standard_ShortReal> (
2435 myRaytraceGeometry.QuadBVH()->NodeInfoBuffer().size() * sizeof (BVH_Vec4i));
2436 aMemBvhUsed += static_cast<Standard_ShortReal> (
2437 myRaytraceGeometry.QuadBVH()->MinPointBuffer().size() * sizeof (BVH_Vec3f));
2438 aMemBvhUsed += static_cast<Standard_ShortReal> (
2439 myRaytraceGeometry.QuadBVH()->MaxPointBuffer().size() * sizeof (BVH_Vec3f));
2440
2441 std::cout << "GPU Memory Used (Mb):\n"
2442 << "\tFor mesh: " << aMemTrgUsed / 1048576 << "\n"
2443 << "\tFor BVHs: " << aMemBvhUsed / 1048576 << "\n";
2444
2445#endif
2446
2447 return aResult;
2448}
2449
2450// =======================================================================
2451// function : updateRaytraceLightSources
2452// purpose : Updates 3D scene light sources for ray-tracing
2453// =======================================================================
2454Standard_Boolean OpenGl_View::updateRaytraceLightSources (const OpenGl_Mat4& theInvModelView, const Handle(OpenGl_Context)& theGlContext)
2455{
2456 std::vector<OpenGl_Light> aLightSources;
2457
2458 if (myShadingModel != Graphic3d_TOSM_NONE)
2459 {
2460 aLightSources.assign (myLights.begin(), myLights.end());
2461
2462 // move positional light sources at the front of the list
2463 std::partition (aLightSources.begin(), aLightSources.end(), IsLightPositional());
2464 }
2465
2466 // get number of 'real' (not ambient) light sources
2467 const size_t aNbLights = std::count_if (aLightSources.begin(), aLightSources.end(), IsNotAmbient());
2468
2469 Standard_Boolean wasUpdated = myRaytraceGeometry.Sources.size () != aNbLights;
2470
2471 if (wasUpdated)
2472 {
2473 myRaytraceGeometry.Sources.resize (aNbLights);
2474 }
2475
2476 myRaytraceGeometry.Ambient = BVH_Vec4f (0.f, 0.f, 0.f, 0.f);
2477
2478 for (size_t aLightIdx = 0, aRealIdx = 0; aLightIdx < aLightSources.size(); ++aLightIdx)
2479 {
2480 const OpenGl_Light& aLight = aLightSources[aLightIdx];
2481
2482 if (aLight.Type == Graphic3d_TOLS_AMBIENT)
2483 {
2484 myRaytraceGeometry.Ambient += BVH_Vec4f (aLight.Color.r() * aLight.Intensity,
2485 aLight.Color.g() * aLight.Intensity,
2486 aLight.Color.b() * aLight.Intensity,
2487 0.0f);
2488 continue;
2489 }
2490
2491 BVH_Vec4f aEmission (aLight.Color.r() * aLight.Intensity,
2492 aLight.Color.g() * aLight.Intensity,
2493 aLight.Color.b() * aLight.Intensity,
2494 1.0f);
2495
2496 BVH_Vec4f aPosition (-aLight.Direction.x(),
2497 -aLight.Direction.y(),
2498 -aLight.Direction.z(),
2499 0.0f);
2500
2501 if (aLight.Type != Graphic3d_TOLS_DIRECTIONAL)
2502 {
2503 aPosition = BVH_Vec4f (static_cast<float>(aLight.Position.x()),
2504 static_cast<float>(aLight.Position.y()),
2505 static_cast<float>(aLight.Position.z()),
2506 1.0f);
2507
2508 // store smoothing radius in W-component
2509 aEmission.w() = Max (aLight.Smoothness, 0.f);
2510 }
2511 else
2512 {
2513 // store cosine of smoothing angle in W-component
2514 aEmission.w() = cosf (Min (Max (aLight.Smoothness, 0.f), static_cast<Standard_ShortReal> (M_PI / 2.0)));
2515 }
2516
2517 if (aLight.IsHeadlight)
2518 {
2519 aPosition = theInvModelView * aPosition;
2520 }
2521
2522 for (int aK = 0; aK < 4; ++aK)
2523 {
2524 wasUpdated |= (aEmission[aK] != myRaytraceGeometry.Sources[aRealIdx].Emission[aK])
2525 || (aPosition[aK] != myRaytraceGeometry.Sources[aRealIdx].Position[aK]);
2526 }
2527
2528 if (wasUpdated)
2529 {
2530 myRaytraceGeometry.Sources[aRealIdx] = OpenGl_RaytraceLight (aEmission, aPosition);
2531 }
2532
2533 ++aRealIdx;
2534 }
2535
2536 if (myRaytraceLightSrcTexture.IsNull()) // create light source buffer
2537 {
2538 myRaytraceLightSrcTexture = new OpenGl_TextureBufferArb;
2539 }
2540
2541 if (myRaytraceGeometry.Sources.size() != 0 && wasUpdated)
2542 {
2543 const GLfloat* aDataPtr = myRaytraceGeometry.Sources.front().Packed();
2544 if (!myRaytraceLightSrcTexture->Init (theGlContext, 4, GLsizei (myRaytraceGeometry.Sources.size() * 2), aDataPtr))
2545 {
2546#ifdef RAY_TRACE_PRINT_INFO
2547 std::cout << "Error: Failed to upload light source buffer" << std::endl;
2548#endif
2549 return Standard_False;
2550 }
2551
2552 myAccumFrames = 0; // accumulation should be restarted
2553 }
2554
2555 return Standard_True;
2556}
2557
2558// =======================================================================
2559// function : setUniformState
2560// purpose : Sets uniform state for the given ray-tracing shader program
2561// =======================================================================
2562Standard_Boolean OpenGl_View::setUniformState (const Standard_Integer theProgramId,
2563 const Standard_Integer theWinSizeX,
2564 const Standard_Integer theWinSizeY,
2565 Graphic3d_Camera::Projection theProjection,
2566 const Handle(OpenGl_Context)& theGlContext)
2567{
2568 // Get projection state
2569 OpenGl_MatrixState<Standard_ShortReal>& aCntxProjectionState = theGlContext->ProjectionState;
2570
2571 OpenGl_Mat4 aViewPrjMat;
2572 OpenGl_Mat4 anUnviewMat;
2573 OpenGl_Vec3 aOrigins[4];
2574 OpenGl_Vec3 aDirects[4];
2575
2576 if (myCamera->IsOrthographic()
2577 || !myRenderParams.IsGlobalIlluminationEnabled)
2578 {
2579 updateCamera (myCamera->OrientationMatrixF(),
2580 aCntxProjectionState.Current(),
2581 aOrigins,
2582 aDirects,
2583 aViewPrjMat,
2584 anUnviewMat);
2585 }
2586 else
2587 {
2588 updatePerspCameraPT (myCamera->OrientationMatrixF(),
2589 aCntxProjectionState.Current(),
2590 theProjection,
2591 aViewPrjMat,
2592 anUnviewMat,
2593 theWinSizeX,
2594 theWinSizeY);
2595 }
2596
2597 Handle(OpenGl_ShaderProgram)& theProgram = theProgramId == 0
2598 ? myRaytraceProgram
2599 : myPostFSAAProgram;
2600
2601 if (theProgram.IsNull())
2602 {
2603 return Standard_False;
2604 }
2605
2606 theProgram->SetUniform(theGlContext, "uEyeOrig", myEyeOrig);
2607 theProgram->SetUniform(theGlContext, "uEyeView", myEyeView);
2608 theProgram->SetUniform(theGlContext, "uEyeVert", myEyeVert);
2609 theProgram->SetUniform(theGlContext, "uEyeSide", myEyeSide);
2610 theProgram->SetUniform(theGlContext, "uEyeSize", myEyeSize);
2611
2612 theProgram->SetUniform(theGlContext, "uApertureRadius", myRenderParams.CameraApertureRadius);
2613 theProgram->SetUniform(theGlContext, "uFocalPlaneDist", myRenderParams.CameraFocalPlaneDist);
2614
2615 // Set camera state
2616 theProgram->SetUniform (theGlContext,
2617 myUniformLocations[theProgramId][OpenGl_RT_uOriginLB], aOrigins[0]);
2618 theProgram->SetUniform (theGlContext,
2619 myUniformLocations[theProgramId][OpenGl_RT_uOriginRB], aOrigins[1]);
2620 theProgram->SetUniform (theGlContext,
2621 myUniformLocations[theProgramId][OpenGl_RT_uOriginLT], aOrigins[2]);
2622 theProgram->SetUniform (theGlContext,
2623 myUniformLocations[theProgramId][OpenGl_RT_uOriginRT], aOrigins[3]);
2624 theProgram->SetUniform (theGlContext,
2625 myUniformLocations[theProgramId][OpenGl_RT_uDirectLB], aDirects[0]);
2626 theProgram->SetUniform (theGlContext,
2627 myUniformLocations[theProgramId][OpenGl_RT_uDirectRB], aDirects[1]);
2628 theProgram->SetUniform (theGlContext,
2629 myUniformLocations[theProgramId][OpenGl_RT_uDirectLT], aDirects[2]);
2630 theProgram->SetUniform (theGlContext,
2631 myUniformLocations[theProgramId][OpenGl_RT_uDirectRT], aDirects[3]);
2632 theProgram->SetUniform (theGlContext,
2633 myUniformLocations[theProgramId][OpenGl_RT_uViewPrMat], aViewPrjMat);
2634 theProgram->SetUniform (theGlContext,
2635 myUniformLocations[theProgramId][OpenGl_RT_uUnviewMat], anUnviewMat);
2636
2637 // Set screen dimensions
2638 myRaytraceProgram->SetUniform (theGlContext,
2639 myUniformLocations[theProgramId][OpenGl_RT_uWinSizeX], theWinSizeX);
2640 myRaytraceProgram->SetUniform (theGlContext,
2641 myUniformLocations[theProgramId][OpenGl_RT_uWinSizeY], theWinSizeY);
2642
2643 // Set 3D scene parameters
2644 theProgram->SetUniform (theGlContext,
2645 myUniformLocations[theProgramId][OpenGl_RT_uSceneRad], myRaytraceSceneRadius);
2646 theProgram->SetUniform (theGlContext,
2647 myUniformLocations[theProgramId][OpenGl_RT_uSceneEps], myRaytraceSceneEpsilon);
2648
2649 // Set light source parameters
2650 const Standard_Integer aLightSourceBufferSize =
2651 static_cast<Standard_Integer> (myRaytraceGeometry.Sources.size());
2652
2653 theProgram->SetUniform (theGlContext,
2654 myUniformLocations[theProgramId][OpenGl_RT_uLightCount], aLightSourceBufferSize);
2655
2656 // Set array of 64-bit texture handles
2657 if (theGlContext->arbTexBindless != NULL && myRaytraceGeometry.HasTextures())
2658 {
2659 const std::vector<GLuint64>& aTextures = myRaytraceGeometry.TextureHandles();
2660
2661 theProgram->SetUniform (theGlContext, myUniformLocations[theProgramId][OpenGl_RT_uTexSamplersArray],
2662 static_cast<GLsizei> (aTextures.size()), reinterpret_cast<const OpenGl_Vec2u*> (&aTextures.front()));
2663 }
2664
2665 // Set background colors (only gradient background supported)
2666 if (myBgGradientArray != NULL && myBgGradientArray->IsDefined())
2667 {
2668 theProgram->SetUniform (theGlContext,
2669 myUniformLocations[theProgramId][OpenGl_RT_uBackColorTop], myBgGradientArray->GradientColor (0));
2670 theProgram->SetUniform (theGlContext,
2671 myUniformLocations[theProgramId][OpenGl_RT_uBackColorBot], myBgGradientArray->GradientColor (1));
2672 }
2673 else
2674 {
2675 const OpenGl_Vec4& aBackColor = myBgColor;
2676
2677 theProgram->SetUniform (theGlContext,
2678 myUniformLocations[theProgramId][OpenGl_RT_uBackColorTop], aBackColor);
2679 theProgram->SetUniform (theGlContext,
2680 myUniformLocations[theProgramId][OpenGl_RT_uBackColorBot], aBackColor);
2681 }
2682
2683 // Set environment map parameters
2684 const Standard_Boolean toDisableEnvironmentMap = myTextureEnv.IsNull() || !myTextureEnv->IsValid();
2685
2686 theProgram->SetUniform (theGlContext,
2687 myUniformLocations[theProgramId][OpenGl_RT_uSphereMapEnabled], toDisableEnvironmentMap ? 0 : 1);
2688
2689 theProgram->SetUniform (theGlContext,
2690 myUniformLocations[theProgramId][OpenGl_RT_uSphereMapForBack], myRenderParams.UseEnvironmentMapBackground ? 1 : 0);
2691
2692 if (myRenderParams.IsGlobalIlluminationEnabled) // GI parameters
2693 {
2694 theProgram->SetUniform (theGlContext,
2695 myUniformLocations[theProgramId][OpenGl_RT_uMaxRadiance], myRenderParams.RadianceClampingValue);
2696
2697 theProgram->SetUniform (theGlContext,
2698 myUniformLocations[theProgramId][OpenGl_RT_uBlockedRngEnabled], myRenderParams.CoherentPathTracingMode ? 1 : 0);
2699
2700 // Check whether we should restart accumulation for run-time parameters
2701 if (myRenderParams.RadianceClampingValue != myRaytraceParameters.RadianceClampingValue
2702 || myRenderParams.UseEnvironmentMapBackground != myRaytraceParameters.UseEnvMapForBackground)
2703 {
2704 myAccumFrames = 0; // accumulation should be restarted
2705
2706 myRaytraceParameters.RadianceClampingValue = myRenderParams.RadianceClampingValue;
2707 myRaytraceParameters.UseEnvMapForBackground = myRenderParams.UseEnvironmentMapBackground;
2708 }
2709 }
2710 else // RT parameters
2711 {
2712 // Set ambient light source
2713 theProgram->SetUniform (theGlContext,
2714 myUniformLocations[theProgramId][OpenGl_RT_uLightAmbnt], myRaytraceGeometry.Ambient);
2715
2716 // Enable/disable run-time ray-tracing effects
2717 theProgram->SetUniform (theGlContext,
2718 myUniformLocations[theProgramId][OpenGl_RT_uShadowsEnabled], myRenderParams.IsShadowEnabled ? 1 : 0);
2719 theProgram->SetUniform (theGlContext,
2720 myUniformLocations[theProgramId][OpenGl_RT_uReflectEnabled], myRenderParams.IsReflectionEnabled ? 1 : 0);
2721 }
2722
2723 return Standard_True;
2724}
2725
2726// =======================================================================
2727// function : bindRaytraceTextures
2728// purpose : Binds ray-trace textures to corresponding texture units
2729// =======================================================================
2730void OpenGl_View::bindRaytraceTextures (const Handle(OpenGl_Context)& theGlContext)
2731{
2732 if (myRaytraceParameters.AdaptiveScreenSampling)
2733 {
2734 #if !defined(GL_ES_VERSION_2_0)
2735 theGlContext->core42->glBindImageTexture (OpenGl_RT_OutputImageLft,
2736 myRaytraceOutputTexture[0]->TextureId(), 0, GL_TRUE, 0, GL_READ_WRITE, GL_R32F);
2737 theGlContext->core42->glBindImageTexture (OpenGl_RT_OutputImageRgh,
2738 myRaytraceOutputTexture[1]->TextureId(), 0, GL_TRUE, 0, GL_READ_WRITE, GL_R32F);
2739
2740 theGlContext->core42->glBindImageTexture (OpenGl_RT_VisualErrorImageLft,
2741 myRaytraceVisualErrorTexture[0]->TextureId(), 0, GL_TRUE, 0, GL_READ_WRITE, GL_R32I);
2742 theGlContext->core42->glBindImageTexture (OpenGl_RT_VisualErrorImageRgh,
2743 myRaytraceVisualErrorTexture[1]->TextureId(), 0, GL_TRUE, 0, GL_READ_WRITE, GL_R32I);
2744 theGlContext->core42->glBindImageTexture (OpenGl_RT_TileOffsetsImageLft,
2745 myRaytraceTileOffsetsTexture[0]->TextureId(), 0, GL_TRUE, 0, GL_READ_ONLY, GL_RG32I);
2746 theGlContext->core42->glBindImageTexture (OpenGl_RT_TileOffsetsImageRgh,
2747 myRaytraceTileOffsetsTexture[1]->TextureId(), 0, GL_TRUE, 0, GL_READ_ONLY, GL_RG32I);
2748#endif
2749 }
2750
2751 if (!myTextureEnv.IsNull() && myTextureEnv->IsValid())
2752 {
2753 myTextureEnv->Bind (theGlContext, GL_TEXTURE0 + OpenGl_RT_EnvironmentMapTexture);
2754 }
2755
2756 mySceneMinPointTexture->BindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_SceneMinPointTexture);
2757 mySceneMaxPointTexture->BindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_SceneMaxPointTexture);
2758 mySceneNodeInfoTexture->BindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_SceneNodeInfoTexture);
2759 myGeometryVertexTexture->BindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryVertexTexture);
2760 myGeometryNormalTexture->BindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryNormalTexture);
2761 myGeometryTexCrdTexture->BindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryTexCrdTexture);
2762 myGeometryTriangTexture->BindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryTriangTexture);
2763 mySceneTransformTexture->BindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_SceneTransformTexture);
2764 myRaytraceMaterialTexture->BindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_RaytraceMaterialTexture);
2765 myRaytraceLightSrcTexture->BindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_RaytraceLightSrcTexture);
2766}
2767
2768// =======================================================================
2769// function : unbindRaytraceTextures
2770// purpose : Unbinds ray-trace textures from corresponding texture units
2771// =======================================================================
2772void OpenGl_View::unbindRaytraceTextures (const Handle(OpenGl_Context)& theGlContext)
2773{
2774 mySceneMinPointTexture->UnbindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_SceneMinPointTexture);
2775 mySceneMaxPointTexture->UnbindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_SceneMaxPointTexture);
2776 mySceneNodeInfoTexture->UnbindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_SceneNodeInfoTexture);
2777 myGeometryVertexTexture->UnbindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryVertexTexture);
2778 myGeometryNormalTexture->UnbindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryNormalTexture);
2779 myGeometryTexCrdTexture->UnbindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryTexCrdTexture);
2780 myGeometryTriangTexture->UnbindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryTriangTexture);
2781 mySceneTransformTexture->UnbindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_SceneTransformTexture);
2782 myRaytraceMaterialTexture->UnbindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_RaytraceMaterialTexture);
2783 myRaytraceLightSrcTexture->UnbindTexture (theGlContext, GL_TEXTURE0 + OpenGl_RT_RaytraceLightSrcTexture);
2784
2785 theGlContext->core15fwd->glActiveTexture (GL_TEXTURE0);
2786}
2787
2788// =======================================================================
2789// function : runRaytraceShaders
2790// purpose : Runs ray-tracing shader programs
2791// =======================================================================
2792Standard_Boolean OpenGl_View::runRaytraceShaders (const Standard_Integer theSizeX,
2793 const Standard_Integer theSizeY,
2794 Graphic3d_Camera::Projection theProjection,
2795 OpenGl_FrameBuffer* theReadDrawFbo,
2796 const Handle(OpenGl_Context)& theGlContext)
2797{
2798 Standard_Boolean aResult = theGlContext->BindProgram (myRaytraceProgram);
2799
2800 aResult &= setUniformState (0,
2801 theSizeX,
2802 theSizeY,
2803 theProjection,
2804 theGlContext);
2805
2806 if (myRaytraceParameters.GlobalIllumination) // path tracing
2807 {
2808 aResult &= runPathtrace (theSizeX, theSizeY, theProjection, theReadDrawFbo, theGlContext);
2809 }
2810 else // Whitted-style ray-tracing
2811 {
2812 aResult &= runRaytrace (theSizeX, theSizeY, theProjection, theReadDrawFbo, theGlContext);
2813 }
2814
2815 return aResult;
2816}
2817
2818// =======================================================================
2819// function : runRaytrace
2820// purpose : Runs Whitted-style ray-tracing
2821// =======================================================================
2822Standard_Boolean OpenGl_View::runRaytrace (const Standard_Integer theSizeX,
2823 const Standard_Integer theSizeY,
2824 Graphic3d_Camera::Projection theProjection,
2825 OpenGl_FrameBuffer* theReadDrawFbo,
2826 const Handle(OpenGl_Context)& theGlContext)
2827{
2828 Standard_Boolean aResult = Standard_True;
2829
2830 bindRaytraceTextures (theGlContext);
2831
2832 Handle(OpenGl_FrameBuffer) aRenderImageFramebuffer;
2833 Handle(OpenGl_FrameBuffer) aDepthSourceFramebuffer;
2834
2835 // Choose proper set of frame buffers for stereo rendering
2836 const Standard_Integer aFBOIdx (theProjection == Graphic3d_Camera::Projection_MonoRightEye);
2837
2838 if (myRenderParams.IsAntialiasingEnabled) // if second FSAA pass is used
2839 {
2840 myRaytraceFBO1[aFBOIdx]->BindBuffer (theGlContext);
2841
2842 glClear (GL_DEPTH_BUFFER_BIT); // render the image with depth
2843 }
2844
2845 theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
2846
2847 if (myRenderParams.IsAntialiasingEnabled)
2848 {
2849 glDisable (GL_DEPTH_TEST); // improve jagged edges without depth buffer
2850
2851 // bind ray-tracing output image as input
2852 myRaytraceFBO1[aFBOIdx]->ColorTexture()->Bind (theGlContext, GL_TEXTURE0 + OpenGl_RT_FsaaInputTexture);
2853
2854 aResult &= theGlContext->BindProgram (myPostFSAAProgram);
2855
2856 aResult &= setUniformState (1 /* FSAA ID */,
2857 theSizeX,
2858 theSizeY,
2859 theProjection,
2860 theGlContext);
2861
2862 // Perform multi-pass adaptive FSAA using ping-pong technique.
2863 // We use 'FLIPTRI' sampling pattern changing for every pixel
2864 // (3 additional samples per pixel, the 1st sample is already
2865 // available from initial ray-traced image).
2866 for (Standard_Integer anIt = 1; anIt < 4; ++anIt)
2867 {
2868 GLfloat aOffsetX = 1.f / theSizeX;
2869 GLfloat aOffsetY = 1.f / theSizeY;
2870
2871 if (anIt == 1)
2872 {
2873 aOffsetX *= -0.55f;
2874 aOffsetY *= 0.55f;
2875 }
2876 else if (anIt == 2)
2877 {
2878 aOffsetX *= 0.00f;
2879 aOffsetY *= -0.55f;
2880 }
2881 else if (anIt == 3)
2882 {
2883 aOffsetX *= 0.55f;
2884 aOffsetY *= 0.00f;
2885 }
2886
2887 aResult &= myPostFSAAProgram->SetUniform (theGlContext,
2888 myUniformLocations[1][OpenGl_RT_uSamples], anIt + 1);
2889 aResult &= myPostFSAAProgram->SetUniform (theGlContext,
2890 myUniformLocations[1][OpenGl_RT_uOffsetX], aOffsetX);
2891 aResult &= myPostFSAAProgram->SetUniform (theGlContext,
2892 myUniformLocations[1][OpenGl_RT_uOffsetY], aOffsetY);
2893
2894 Handle(OpenGl_FrameBuffer)& aFramebuffer = anIt % 2
2895 ? myRaytraceFBO2[aFBOIdx]
2896 : myRaytraceFBO1[aFBOIdx];
2897
2898 aFramebuffer->BindBuffer (theGlContext);
2899
2900 // perform adaptive FSAA pass
2901 theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
2902
2903 aFramebuffer->ColorTexture()->Bind (theGlContext, GL_TEXTURE0 + OpenGl_RT_FsaaInputTexture);
2904 }
2905
2906 aRenderImageFramebuffer = myRaytraceFBO2[aFBOIdx];
2907 aDepthSourceFramebuffer = myRaytraceFBO1[aFBOIdx];
2908
2909 glEnable (GL_DEPTH_TEST);
2910
2911 // Display filtered image
2912 theGlContext->BindProgram (myOutImageProgram);
2913
2914 if (theReadDrawFbo != NULL)
2915 {
2916 theReadDrawFbo->BindBuffer (theGlContext);
2917 }
2918 else
2919 {
2920 aRenderImageFramebuffer->UnbindBuffer (theGlContext);
2921 }
2922
2923 aRenderImageFramebuffer->ColorTexture()->Bind (
2924 theGlContext, GL_TEXTURE0 + OpenGl_RT_PrevAccumTexture);
2925
2926 aDepthSourceFramebuffer->DepthStencilTexture()->Bind (
2927 theGlContext, GL_TEXTURE0 + OpenGl_RT_RaytraceDepthTexture);
2928
2929 // copy the output image with depth values
2930 theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
2931
2932 aDepthSourceFramebuffer->DepthStencilTexture()->Unbind (
2933 theGlContext, GL_TEXTURE0 + OpenGl_RT_RaytraceDepthTexture);
2934
2935 aRenderImageFramebuffer->ColorTexture()->Unbind (
2936 theGlContext, GL_TEXTURE0 + OpenGl_RT_PrevAccumTexture);
2937 }
2938
2939 unbindRaytraceTextures (theGlContext);
2940
2941 theGlContext->BindProgram (NULL);
2942
2943 return aResult;
2944}
2945
2946// =======================================================================
2947// function : runPathtrace
2948// purpose : Runs path tracing shader
2949// =======================================================================
2950Standard_Boolean OpenGl_View::runPathtrace (const Standard_Integer theSizeX,
2951 const Standard_Integer theSizeY,
2952 const Graphic3d_Camera::Projection theProjection,
2953 OpenGl_FrameBuffer* theReadDrawFbo,
2954 const Handle(OpenGl_Context)& theGlContext)
2955{
2956 Standard_Boolean aResult = Standard_True;
2957
2958 if (myToUpdateEnvironmentMap) // check whether the map was changed
2959 {
2960 myAccumFrames = myToUpdateEnvironmentMap = 0;
2961 }
2962
2963 if (myRenderParams.CameraApertureRadius != myPrevCameraApertureRadius
2964 || myRenderParams.CameraFocalPlaneDist != myPrevCameraFocalPlaneDist)
2965 {
2966
2967 myPrevCameraApertureRadius = myRenderParams.CameraApertureRadius;
2968 myPrevCameraFocalPlaneDist = myRenderParams.CameraFocalPlaneDist;
2969
2970 myAccumFrames = 0;
2971 }
2972
2973 // Choose proper set of frame buffers for stereo rendering
2974 const Standard_Integer aFBOIdx (theProjection == Graphic3d_Camera::Projection_MonoRightEye);
2975
2976 if (myRaytraceParameters.AdaptiveScreenSampling)
2977 {
2978 if (myAccumFrames == 0)
2979 {
2980 myTileSampler.Reset(); // reset tile sampler to its initial state
2981
2982 // Adaptive sampling is starting at the second frame
2983 myTileSampler.Upload (theGlContext,
2984 myRaytraceTileOffsetsTexture[aFBOIdx],
2985 myRaytraceParameters.NbTilesX,
2986 myRaytraceParameters.NbTilesY,
2987 false);
2988 }
2989 }
2990
2991 bindRaytraceTextures (theGlContext);
2992
2993 Handle(OpenGl_FrameBuffer) aRenderImageFramebuffer;
2994 Handle(OpenGl_FrameBuffer) aDepthSourceFramebuffer;
2995 Handle(OpenGl_FrameBuffer) anAccumImageFramebuffer;
2996
2997 const Standard_Integer anImageId = (aFBOIdx != 0)
2998 ? OpenGl_RT_OutputImageRgh
2999 : OpenGl_RT_OutputImageLft;
3000
3001 const Standard_Integer anErrorId = (aFBOIdx != 0)
3002 ? OpenGl_RT_VisualErrorImageRgh
3003 : OpenGl_RT_VisualErrorImageLft;
3004
3005 const Standard_Integer anOffsetId = (aFBOIdx != 0)
3006 ? OpenGl_RT_TileOffsetsImageRgh
3007 : OpenGl_RT_TileOffsetsImageLft;
3008
3009 aRenderImageFramebuffer = myAccumFrames % 2 ? myRaytraceFBO1[aFBOIdx] : myRaytraceFBO2[aFBOIdx];
3010 anAccumImageFramebuffer = myAccumFrames % 2 ? myRaytraceFBO2[aFBOIdx] : myRaytraceFBO1[aFBOIdx];
3011
3012 aDepthSourceFramebuffer = aRenderImageFramebuffer;
3013
3014 anAccumImageFramebuffer->ColorTexture()->Bind (
3015 theGlContext, GL_TEXTURE0 + OpenGl_RT_PrevAccumTexture);
3016
3017 aRenderImageFramebuffer->BindBuffer (theGlContext);
3018
3019 if (myAccumFrames == 0)
3020 {
3021 myRNG.SetSeed(); // start RNG from beginning
3022 }
3023
3024 // Clear adaptive screen sampling images
3025 if (myRaytraceParameters.AdaptiveScreenSampling)
3026 {
3027 #if !defined(GL_ES_VERSION_2_0)
3028 if (myAccumFrames == 0 || (myAccumFrames == 1 && myCamera->IsStereo()))
3029 {
3030 theGlContext->core44->glClearTexImage (myRaytraceOutputTexture[aFBOIdx]->TextureId(), 0, GL_RED, GL_FLOAT, NULL);
3031 }
3032
3033 theGlContext->core44->glClearTexImage (myRaytraceVisualErrorTexture[aFBOIdx]->TextureId(), 0, GL_RED_INTEGER, GL_INT, NULL);
3034 #endif
3035 }
3036
3037 // Set frame accumulation weight
3038 myRaytraceProgram->SetUniform (theGlContext,
3039 myUniformLocations[0][OpenGl_RT_uAccumSamples], myAccumFrames);
3040
3041 // Set random number generator seed
3042 myRaytraceProgram->SetUniform (theGlContext,
3043 myUniformLocations[0][OpenGl_RT_uFrameRndSeed], static_cast<Standard_Integer> (myRNG.NextInt() >> 2));
3044
3045 // Set image uniforms for render program
3046 myRaytraceProgram->SetUniform (theGlContext,
3047 myUniformLocations[0][OpenGl_RT_uRenderImage], anImageId);
3048 myRaytraceProgram->SetUniform (theGlContext,
3049 myUniformLocations[0][OpenGl_RT_uOffsetImage], anOffsetId);
3050
3051 glDisable (GL_DEPTH_TEST);
3052
3053 if (myRaytraceParameters.AdaptiveScreenSampling
3054 && ((myAccumFrames > 0 && !myCamera->IsStereo()) || myAccumFrames > 1))
3055 {
3056 glViewport (0,
3057 0,
3058 myTileSampler.TileSize() * myRaytraceParameters.NbTilesX,
3059 myTileSampler.TileSize() * myRaytraceParameters.NbTilesY);
3060 }
3061
3062 // Generate for the given RNG seed
3063 theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
3064
3065 if (myRaytraceParameters.AdaptiveScreenSampling
3066 && ((myAccumFrames > 0 && !myCamera->IsStereo()) || myAccumFrames > 1))
3067 {
3068 glViewport (0,
3069 0,
3070 theSizeX,
3071 theSizeY);
3072 }
3073
3074 // Output accumulated path traced image
3075 theGlContext->BindProgram (myOutImageProgram);
3076
3077 if (myRaytraceParameters.AdaptiveScreenSampling)
3078 {
3079 // Set uniforms for display program
3080 myOutImageProgram->SetUniform (theGlContext, "uRenderImage", anImageId);
3081 myOutImageProgram->SetUniform (theGlContext, "uAccumFrames", myAccumFrames);
3082 myOutImageProgram->SetUniform (theGlContext, "uVarianceImage", anErrorId);
3083 myOutImageProgram->SetUniform (theGlContext, "uDebugAdaptive", myRenderParams.ShowSamplingTiles ? 1 : 0);
3084 }
3085
3086 if (myRaytraceParameters.GlobalIllumination)
3087 {
3088 myOutImageProgram->SetUniform(theGlContext, "uExposure", myRenderParams.Exposure);
3089 switch (myRaytraceParameters.ToneMappingMethod)
3090 {
3091 case Graphic3d_ToneMappingMethod_Disabled:
3092 break;
3093 case Graphic3d_ToneMappingMethod_Filmic:
3094 myOutImageProgram->SetUniform (theGlContext, "uWhitePoint", myRenderParams.WhitePoint);
3095 break;
3096 }
3097 }
3098
3099 if (theReadDrawFbo != NULL)
3100 {
3101 theReadDrawFbo->BindBuffer (theGlContext);
3102 }
3103 else
3104 {
3105 aRenderImageFramebuffer->UnbindBuffer (theGlContext);
3106 }
3107
3108 aRenderImageFramebuffer->ColorTexture()->Bind (
3109 theGlContext, GL_TEXTURE0 + OpenGl_RT_PrevAccumTexture);
3110
3111 glEnable (GL_DEPTH_TEST);
3112
3113 // Copy accumulated image with correct depth values
3114 theGlContext->core20fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
3115
3116 aRenderImageFramebuffer->ColorTexture()->Unbind (
3117 theGlContext, GL_TEXTURE0 + OpenGl_RT_PrevAccumTexture);
3118
3119 if (myRaytraceParameters.AdaptiveScreenSampling)
3120 {
3121 myRaytraceVisualErrorTexture[aFBOIdx]->Bind (theGlContext);
3122
3123 // Download visual error map from the GPU and build
3124 // adjusted tile offsets for optimal image sampling
3125 myTileSampler.GrabVarianceMap (theGlContext);
3126
3127 myTileSampler.Upload (theGlContext,
3128 myRaytraceTileOffsetsTexture[aFBOIdx],
3129 myRaytraceParameters.NbTilesX,
3130 myRaytraceParameters.NbTilesY,
3131 myAccumFrames > 0);
3132 }
3133
3134 unbindRaytraceTextures (theGlContext);
3135
3136 theGlContext->BindProgram (NULL);
3137
3138 return aResult;
3139}
3140
3141// =======================================================================
3142// function : raytrace
3143// purpose : Redraws the window using OpenGL/GLSL ray-tracing
3144// =======================================================================
3145Standard_Boolean OpenGl_View::raytrace (const Standard_Integer theSizeX,
3146 const Standard_Integer theSizeY,
3147 Graphic3d_Camera::Projection theProjection,
3148 OpenGl_FrameBuffer* theReadDrawFbo,
3149 const Handle(OpenGl_Context)& theGlContext)
3150{
3151 if (!initRaytraceResources (theGlContext))
3152 {
3153 return Standard_False;
3154 }
3155
3156 if (!updateRaytraceBuffers (theSizeX, theSizeY, theGlContext))
3157 {
3158 return Standard_False;
3159 }
3160
3161 OpenGl_Mat4 aLightSourceMatrix;
3162
3163 // Get inversed model-view matrix for transforming lights
3164 myCamera->OrientationMatrixF().Inverted (aLightSourceMatrix);
3165
3166 if (!updateRaytraceLightSources (aLightSourceMatrix, theGlContext))
3167 {
3168 return Standard_False;
3169 }
3170
3171 // Generate image using Whitted-style ray-tracing or path tracing
3172 if (myIsRaytraceDataValid)
3173 {
3174 myRaytraceScreenQuad.BindVertexAttrib (theGlContext, Graphic3d_TOA_POS);
3175
3176 if (!myRaytraceGeometry.AcquireTextures (theGlContext))
3177 {
3178 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR,
3179 0, GL_DEBUG_SEVERITY_MEDIUM, "Error: Failed to acquire OpenGL image textures");
3180 }
3181
3182 glDisable (GL_BLEND);
3183
3184 const Standard_Boolean aResult = runRaytraceShaders (theSizeX,
3185 theSizeY,
3186 theProjection,
3187 theReadDrawFbo,
3188 theGlContext);
3189
3190 if (!aResult)
3191 {
3192 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR,
3193 0, GL_DEBUG_SEVERITY_MEDIUM, "Error: Failed to execute ray-tracing shaders");
3194 }
3195
3196 if (!myRaytraceGeometry.ReleaseTextures (theGlContext))
3197 {
3198 theGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_ERROR,
3199 0, GL_DEBUG_SEVERITY_MEDIUM, "Error: Failed to release OpenGL image textures");
3200 }
3201
3202 myRaytraceScreenQuad.UnbindVertexAttrib (theGlContext, Graphic3d_TOA_POS);
3203 }
3204
3205 return Standard_True;
3206}