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