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