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