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