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