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