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