0025258: Uninitialized class field in IntPatch_CSFunction
[occt.git] / src / OpenGl / OpenGl_Workspace_Raytrace.cxx
CommitLineData
e276548b 1// Created on: 2013-08-27
2// Created by: Denis BOGOLEPOV
3// Copyright (c) 2013 OPEN CASCADE SAS
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
b7cd4ba7 16#include <OpenGl_Workspace.hxx>
17
fc73a202 18#include <NCollection_Mat4.hxx>
19#include <OpenGl_ArbFBO.hxx>
20#include <OpenGl_FrameBuffer.hxx>
b7cd4ba7 21#include <OpenGl_PrimitiveArray.hxx>
e276548b 22#include <OpenGl_Texture.hxx>
fc73a202 23#include <OpenGl_VertexBuffer.hxx>
e276548b 24#include <OpenGl_View.hxx>
fc73a202 25#include <OSD_File.hxx>
26#include <OSD_Protection.hxx>
265d4508 27#include <Standard_Assert.hxx>
e276548b 28
29using namespace OpenGl_Raytrace;
30
31//! Use this macro to output ray-tracing debug info
fc73a202 32// #define RAY_TRACE_PRINT_INFO
e276548b 33
34#ifdef RAY_TRACE_PRINT_INFO
35 #include <OSD_Timer.hxx>
36#endif
37
e276548b 38// =======================================================================
39// function : MatVecMult
40// purpose : Multiples 4x4 matrix by 4D vector
41// =======================================================================
265d4508 42template<typename T>
43BVH_Vec4f MatVecMult (const T m[16], const BVH_Vec4f& v)
e276548b 44{
265d4508 45 return BVH_Vec4f (
e276548b 46 static_cast<float> (m[ 0] * v.x() + m[ 4] * v.y() +
47 m[ 8] * v.z() + m[12] * v.w()),
48 static_cast<float> (m[ 1] * v.x() + m[ 5] * v.y() +
49 m[ 9] * v.z() + m[13] * v.w()),
50 static_cast<float> (m[ 2] * v.x() + m[ 6] * v.y() +
51 m[10] * v.z() + m[14] * v.w()),
52 static_cast<float> (m[ 3] * v.x() + m[ 7] * v.y() +
53 m[11] * v.z() + m[15] * v.w()));
54}
55
56// =======================================================================
e276548b 57// function : UpdateRaytraceGeometry
58// purpose : Updates 3D scene geometry for ray tracing
59// =======================================================================
84c71f29 60Standard_Boolean OpenGl_Workspace::UpdateRaytraceGeometry (GeomUpdateMode theMode)
e276548b 61{
62 if (myView.IsNull())
63 return Standard_False;
64
84c71f29 65 // Note: In 'check' mode (OpenGl_GUM_CHECK) the scene geometry is analyzed for modifications
e276548b 66 // This is light-weight procedure performed for each frame
67
84c71f29 68 if (theMode == OpenGl_GUM_CHECK)
e276548b 69 {
84c71f29 70 if (myLayersModificationStatus != myView->LayerList().ModificationState())
71 {
72 return UpdateRaytraceGeometry (OpenGl_GUM_PREPARE);
73 }
74 }
75 else if (theMode == OpenGl_GUM_PREPARE)
76 {
77 myRaytraceGeometry.ClearMaterials();
78 myArrayToTrianglesMap.clear();
e276548b 79
80 myIsRaytraceDataValid = Standard_False;
81 }
e276548b 82
83 // The set of processed structures (reflected to ray-tracing)
84 // This set is used to remove out-of-date records from the
85 // hash map of structures
86 std::set<const OpenGl_Structure*> anElements;
87
84c71f29 88 // Set of all currently visible and "raytracable" primitive arrays.
8d3f219f 89 std::set<Standard_Size> anArrayIDs;
84c71f29 90
e276548b 91 const OpenGl_LayerList& aList = myView->LayerList();
92
93 for (OpenGl_SequenceOfLayers::Iterator anLayerIt (aList.Layers()); anLayerIt.More(); anLayerIt.Next())
94 {
c5751993 95 const OpenGl_PriorityList& aPriorityList = anLayerIt.Value().PriorityList();
e276548b 96
97 if (aPriorityList.NbStructures() == 0)
98 continue;
99
100 const OpenGl_ArrayOfStructure& aStructArray = aPriorityList.ArrayOfStructures();
101
68333c8f 102 for (Standard_Integer anIndex = 0; anIndex < aStructArray.Length(); ++anIndex)
e276548b 103 {
104 OpenGl_SequenceOfStructure::Iterator aStructIt;
105
106 for (aStructIt.Init (aStructArray (anIndex)); aStructIt.More(); aStructIt.Next())
107 {
108 const OpenGl_Structure* aStructure = aStructIt.Value();
109
84c71f29 110 if (theMode == OpenGl_GUM_CHECK)
e276548b 111 {
112 if (CheckRaytraceStructure (aStructure))
113 {
84c71f29 114 return UpdateRaytraceGeometry (OpenGl_GUM_PREPARE);
e276548b 115 }
84c71f29 116 }
117 else if (theMode == OpenGl_GUM_PREPARE)
118 {
119 if (!aStructure->IsRaytracable()
120 || !aStructure->IsVisible())
121 continue;
122
123 for (OpenGl_Structure::GroupIterator aGroupIter (aStructure->DrawGroups()); aGroupIter.More(); aGroupIter.Next())
124 {
125 // OpenGL elements from group (extract primitives arrays)
126 for (const OpenGl_ElementNode* aNode = aGroupIter.Value()->FirstNode(); aNode != NULL; aNode = aNode->next)
127 {
128 OpenGl_PrimitiveArray* aPrimArray = dynamic_cast<OpenGl_PrimitiveArray*> (aNode->elem);
129
130 if (aPrimArray != NULL)
131 {
132 // Collect all primitive arrays in scene.
8d3f219f 133 anArrayIDs.insert (aPrimArray->GetUID());
84c71f29 134 }
135 }
136 }
137 }
138 else if (theMode == OpenGl_GUM_UPDATE)
e276548b 139 {
140 if (!aStructure->IsRaytracable())
141 continue;
142
0717ddc1 143 AddRaytraceStructure (aStructure, anElements);
e276548b 144 }
145 }
146 }
147 }
148
84c71f29 149 if (theMode == OpenGl_GUM_PREPARE)
150 {
151 BVH_ObjectSet<Standard_ShortReal, 4>::BVH_ObjectList anUnchangedObjects;
152
153 // Leave only unchanged objects in myRaytraceGeometry so only their transforms and materials will be updated
154 // Objects which not in myArrayToTrianglesMap will be built from scratch.
155 for (Standard_Integer anObjectIdx = 0; anObjectIdx < myRaytraceGeometry.Objects().Size(); ++anObjectIdx)
156 {
157 OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
158 myRaytraceGeometry.Objects().ChangeValue (anObjectIdx).operator->());
159
160 // If primitive array of object not in "anArrays" set then it was hided or deleted.
161 // If primitive array present in "anArrays" set but we don't have associated object yet, then
162 // the object is new and still has to be built.
8d3f219f 163 if ((aTriangleSet != NULL) && ((anArrayIDs.find (aTriangleSet->AssociatedPArrayID())) != anArrayIDs.end()))
84c71f29 164 {
165 anUnchangedObjects.Append (myRaytraceGeometry.Objects().Value (anObjectIdx));
166
8d3f219f 167 myArrayToTrianglesMap[aTriangleSet->AssociatedPArrayID()] = aTriangleSet;
84c71f29 168 }
169 }
170
171 myRaytraceGeometry.Objects() = anUnchangedObjects;
172
173 return UpdateRaytraceGeometry (OpenGl_GUM_UPDATE);
174 }
175
176 if (theMode == OpenGl_GUM_UPDATE)
e276548b 177 {
178 // Actualize the hash map of structures -- remove out-of-date records
179 std::map<const OpenGl_Structure*, Standard_Size>::iterator anIter = myStructureStates.begin();
180
181 while (anIter != myStructureStates.end())
182 {
183 if (anElements.find (anIter->first) == anElements.end())
184 {
185 myStructureStates.erase (anIter++);
186 }
187 else
188 {
189 ++anIter;
190 }
191 }
192
193 // Actualize OpenGL layer list state
194 myLayersModificationStatus = myView->LayerList().ModificationState();
195
265d4508 196 // Rebuild bottom-level and high-level BVHs
197 myRaytraceGeometry.ProcessAcceleration();
e276548b 198
265d4508 199 const Standard_ShortReal aMinRadius = Max (fabs (myRaytraceGeometry.Box().CornerMin().x()), Max (
200 fabs (myRaytraceGeometry.Box().CornerMin().y()), fabs (myRaytraceGeometry.Box().CornerMin().z())));
201 const Standard_ShortReal aMaxRadius = Max (fabs (myRaytraceGeometry.Box().CornerMax().x()), Max (
202 fabs (myRaytraceGeometry.Box().CornerMax().y()), fabs (myRaytraceGeometry.Box().CornerMax().z())));
e276548b 203
265d4508 204 myRaytraceSceneRadius = 2.f /* scale factor */ * Max (aMinRadius, aMaxRadius);
e276548b 205
fc73a202 206 const BVH_Vec4f aSize = myRaytraceGeometry.Box().Size();
e276548b 207
a89742cf 208 myRaytraceSceneEpsilon = Max (1e-6f, 1e-4f * sqrtf (
fc73a202 209 aSize.x() * aSize.x() + aSize.y() * aSize.y() + aSize.z() * aSize.z()));
210
211 return UploadRaytraceData();
e276548b 212 }
213
e276548b 214 return Standard_True;
215}
216
217// =======================================================================
218// function : CheckRaytraceStructure
265d4508 219// purpose : Checks to see if the structure is modified
e276548b 220// =======================================================================
221Standard_Boolean OpenGl_Workspace::CheckRaytraceStructure (const OpenGl_Structure* theStructure)
222{
223 if (!theStructure->IsRaytracable())
224 {
225 // Checks to see if all ray-tracable elements were
226 // removed from the structure
227 if (theStructure->ModificationState() > 0)
228 {
229 theStructure->ResetModificationState();
230 return Standard_True;
231 }
232
233 return Standard_False;
234 }
235
236 std::map<const OpenGl_Structure*, Standard_Size>::iterator aStructState = myStructureStates.find (theStructure);
237
238 if (aStructState != myStructureStates.end())
239 return aStructState->second != theStructure->ModificationState();
240
241 return Standard_True;
242}
243
244// =======================================================================
245// function : CreateMaterial
246// purpose : Creates ray-tracing material properties
247// =======================================================================
265d4508 248void CreateMaterial (const OPENGL_SURF_PROP& theProp, OpenGl_RaytraceMaterial& theMaterial)
e276548b 249{
64c759f8 250 const float* aSrcAmb = theProp.isphysic ? theProp.ambcol.rgb : theProp.matcol.rgb;
265d4508 251 theMaterial.Ambient = BVH_Vec4f (aSrcAmb[0] * theProp.amb,
252 aSrcAmb[1] * theProp.amb,
253 aSrcAmb[2] * theProp.amb,
254 1.0f);
64c759f8 255
256 const float* aSrcDif = theProp.isphysic ? theProp.difcol.rgb : theProp.matcol.rgb;
265d4508 257 theMaterial.Diffuse = BVH_Vec4f (aSrcDif[0] * theProp.diff,
258 aSrcDif[1] * theProp.diff,
259 aSrcDif[2] * theProp.diff,
260 1.0f);
64c759f8 261
262 const float aDefSpecCol[4] = {1.0f, 1.0f, 1.0f, 1.0f};
263 const float* aSrcSpe = theProp.isphysic ? theProp.speccol.rgb : aDefSpecCol;
265d4508 264 theMaterial.Specular = BVH_Vec4f (aSrcSpe[0] * theProp.spec,
265 aSrcSpe[1] * theProp.spec,
266 aSrcSpe[2] * theProp.spec,
267 theProp.shine);
e276548b 268
64c759f8 269 const float* aSrcEms = theProp.isphysic ? theProp.emscol.rgb : theProp.matcol.rgb;
265d4508 270 theMaterial.Emission = BVH_Vec4f (aSrcEms[0] * theProp.emsv,
271 aSrcEms[1] * theProp.emsv,
272 aSrcEms[2] * theProp.emsv,
273 1.0f);
e276548b 274
275 // Note: Here we use sub-linear transparency function
276 // to produce realistic-looking transparency effect
265d4508 277 theMaterial.Transparency = BVH_Vec4f (powf (theProp.trans, 0.75f),
278 1.f - theProp.trans,
dc9ef964 279 theProp.index == 0 ? 1.f : theProp.index,
280 theProp.index == 0 ? 1.f : 1.f / theProp.index);
e276548b 281
282 const float aMaxRefl = Max (theMaterial.Diffuse.x() + theMaterial.Specular.x(),
283 Max (theMaterial.Diffuse.y() + theMaterial.Specular.y(),
284 theMaterial.Diffuse.z() + theMaterial.Specular.z()));
285
286 const float aReflectionScale = 0.75f / aMaxRefl;
287
fc73a202 288 theMaterial.Reflection = BVH_Vec4f (theProp.speccol.rgb[0] * theProp.spec * aReflectionScale,
289 theProp.speccol.rgb[1] * theProp.spec * aReflectionScale,
290 theProp.speccol.rgb[2] * theProp.spec * aReflectionScale,
291 0.f);
e276548b 292}
293
294// =======================================================================
295// function : AddRaytraceStructure
296// purpose : Adds OpenGL structure to ray-traced scene geometry
297// =======================================================================
0717ddc1 298Standard_Boolean OpenGl_Workspace::AddRaytraceStructure (const OpenGl_Structure* theStructure, std::set<const OpenGl_Structure*>& theElements)
e276548b 299{
e276548b 300 theElements.insert (theStructure);
301
302 if (!theStructure->IsVisible())
303 {
304 myStructureStates[theStructure] = theStructure->ModificationState();
305 return Standard_True;
306 }
307
308 // Get structure material
68333c8f 309 Standard_Integer aStructMatID = -1;
e276548b 310
311 if (theStructure->AspectFace() != NULL)
312 {
265d4508 313 aStructMatID = static_cast<Standard_Integer> (myRaytraceGeometry.Materials.size());
e276548b 314
315 OpenGl_RaytraceMaterial aStructMaterial;
316 CreateMaterial (theStructure->AspectFace()->IntFront(), aStructMaterial);
317
265d4508 318 myRaytraceGeometry.Materials.push_back (aStructMaterial);
e276548b 319 }
320
0717ddc1 321 Standard_ShortReal aStructTransformArr[16];
322 Standard_ShortReal* aStructTransform = NULL;
323 if (theStructure->Transformation()->mat != NULL)
324 {
325 aStructTransform = aStructTransformArr;
326 for (Standard_Integer i = 0; i < 4; ++i)
327 {
328 for (Standard_Integer j = 0; j < 4; ++j)
329 {
330 aStructTransform[j * 4 + i] = theStructure->Transformation()->mat[i][j];
331 }
332 }
333 }
334
335 AddRaytraceGroups (theStructure, aStructMatID, aStructTransform);
336
337 // Process all connected OpenGL structures
338 for (OpenGl_ListOfStructure::Iterator anIts (theStructure->ConnectedStructures()); anIts.More(); anIts.Next())
339 {
340 if (anIts.Value()->IsRaytracable())
341 AddRaytraceGroups (anIts.Value(), aStructMatID, aStructTransform);
342 }
343
344 myStructureStates[theStructure] = theStructure->ModificationState();
345 return Standard_True;
346}
347
348// =======================================================================
349// function : AddRaytraceGroups
350// purpose : Adds OpenGL groups to ray-traced scene geometry
351// =======================================================================
352Standard_Boolean OpenGl_Workspace::AddRaytraceGroups (const OpenGl_Structure* theStructure,
353 const Standard_Integer theStructMatId,
354 const Standard_ShortReal* theTransform)
355{
b64d84be 356 for (OpenGl_Structure::GroupIterator aGroupIter (theStructure->DrawGroups()); aGroupIter.More(); aGroupIter.Next())
e276548b 357 {
358 // Get group material
68333c8f 359 Standard_Integer aGroupMatID = -1;
b64d84be 360 if (aGroupIter.Value()->AspectFace() != NULL)
e276548b 361 {
265d4508 362 aGroupMatID = static_cast<Standard_Integer> (myRaytraceGeometry.Materials.size());
e276548b 363
364 OpenGl_RaytraceMaterial aGroupMaterial;
b64d84be 365 CreateMaterial (aGroupIter.Value()->AspectFace()->IntFront(), aGroupMaterial);
e276548b 366
265d4508 367 myRaytraceGeometry.Materials.push_back (aGroupMaterial);
e276548b 368 }
369
0717ddc1 370 Standard_Integer aMatID = aGroupMatID < 0 ? theStructMatId : aGroupMatID;
e276548b 371
265d4508 372 if (aMatID < 0)
e276548b 373 {
265d4508 374 aMatID = static_cast<Standard_Integer> (myRaytraceGeometry.Materials.size());
e276548b 375
265d4508 376 myRaytraceGeometry.Materials.push_back (OpenGl_RaytraceMaterial());
e276548b 377 }
378
265d4508 379 // Add OpenGL elements from group (extract primitives arrays and aspects)
b64d84be 380 for (const OpenGl_ElementNode* aNode = aGroupIter.Value()->FirstNode(); aNode != NULL; aNode = aNode->next)
e276548b 381 {
5322131b 382 OpenGl_AspectFace* anAspect = dynamic_cast<OpenGl_AspectFace*> (aNode->elem);
383 if (anAspect != NULL)
e276548b 384 {
5322131b 385 aMatID = static_cast<Standard_Integer> (myRaytraceGeometry.Materials.size());
e276548b 386
5322131b 387 OpenGl_RaytraceMaterial aMaterial;
388 CreateMaterial (anAspect->IntFront(), aMaterial);
e276548b 389
5322131b 390 myRaytraceGeometry.Materials.push_back (aMaterial);
e276548b 391 }
5322131b 392 else
e276548b 393 {
394 OpenGl_PrimitiveArray* aPrimArray = dynamic_cast<OpenGl_PrimitiveArray*> (aNode->elem);
84c71f29 395
e276548b 396 if (aPrimArray != NULL)
397 {
8d3f219f 398 std::map<Standard_Size, OpenGl_TriangleSet*>::iterator aSetIter = myArrayToTrianglesMap.find (aPrimArray->GetUID());
399
84c71f29 400 if (aSetIter != myArrayToTrianglesMap.end())
401 {
402 OpenGl_TriangleSet* aSet = aSetIter->second;
403
404 BVH_Transform<Standard_ShortReal, 4>* aTransform = new BVH_Transform<Standard_ShortReal, 4>();
405
406 if (theTransform != NULL)
407 {
408 aTransform->SetTransform (*(reinterpret_cast<const BVH_Mat4f*> (theTransform)));
409 }
410
411 aSet->SetProperties (aTransform);
412
413 if (aSet->MaterialIndex() != OpenGl_TriangleSet::INVALID_MATERIAL && aSet->MaterialIndex() != aMatID )
414 {
415 aSet->SetMaterialIndex (aMatID);
416 }
417 }
418 else
419 {
420 NCollection_Handle<BVH_Object<Standard_ShortReal, 4> > aSet =
421 AddRaytracePrimitiveArray (aPrimArray, aMatID, 0);
265d4508 422
84c71f29 423 if (!aSet.IsNull())
424 {
425 BVH_Transform<Standard_ShortReal, 4>* aTransform = new BVH_Transform<Standard_ShortReal, 4>;
426
427 if (theTransform != NULL)
428 {
429 aTransform->SetTransform (*(reinterpret_cast<const BVH_Mat4f*> (theTransform)));
430 }
431
432 aSet->SetProperties (aTransform);
433
434 myRaytraceGeometry.Objects().Append (aSet);
435 }
436 }
e276548b 437 }
438 }
439 }
e276548b 440 }
441
e276548b 442 return Standard_True;
443}
444
445// =======================================================================
446// function : AddRaytracePrimitiveArray
447// purpose : Adds OpenGL primitive array to ray-traced scene geometry
448// =======================================================================
871fa103 449OpenGl_TriangleSet* OpenGl_Workspace::AddRaytracePrimitiveArray (const OpenGl_PrimitiveArray* theArray,
450 Standard_Integer theMatID,
451 const Standard_ShortReal* theTransform)
e276548b 452{
871fa103 453 const Handle(Graphic3d_IndexBuffer)& anIndices = theArray->Indices();
454 const Handle(Graphic3d_Buffer)& anAttribs = theArray->Attributes();
455 const Handle(Graphic3d_BoundBuffer)& aBounds = theArray->Bounds();
456 if (theArray->DrawMode() < GL_TRIANGLES
457 || theArray->DrawMode() > GL_POLYGON
458 || anAttribs.IsNull())
e276548b 459 {
265d4508 460 return NULL;
e276548b 461 }
462
e276548b 463#ifdef RAY_TRACE_PRINT_INFO
bc8c79bb 464 switch (theArray->DrawMode())
e276548b 465 {
871fa103 466 case GL_POLYGON: std::cout << "\tAdding GL_POLYGON\n"; break;
467 case GL_TRIANGLES: std::cout << "\tAdding GL_TRIANGLES\n"; break;
468 case GL_QUADS: std::cout << "\tAdding GL_QUADS\n"; break;
469 case GL_TRIANGLE_FAN: std::cout << "\tAdding GL_TRIANGLE_FAN\n"; break;
470 case GL_TRIANGLE_STRIP: std::cout << "\tAdding GL_TRIANGLE_STRIP\n"; break;
471 case GL_QUAD_STRIP: std::cout << "\tAdding GL_QUAD_STRIP\n"; break;
e276548b 472 }
473#endif
474
8d3f219f 475 OpenGl_TriangleSet* aSet = new OpenGl_TriangleSet (theArray->GetUID());
e276548b 476 {
871fa103 477 aSet->Vertices.reserve (anAttribs->NbElements);
478 aSet->Normals .reserve (anAttribs->NbElements);
479 const size_t aVertFrom = aSet->Vertices.size();
480 for (Standard_Integer anAttribIter = 0; anAttribIter < anAttribs->NbAttributes; ++anAttribIter)
265d4508 481 {
871fa103 482 const Graphic3d_Attribute& anAttrib = anAttribs->Attribute (anAttribIter);
483 const size_t anOffset = anAttribs->AttributeOffset (anAttribIter);
484 if (anAttrib.Id == Graphic3d_TOA_POS)
485 {
486 if (anAttrib.DataType == Graphic3d_TOD_VEC3
487 || anAttrib.DataType == Graphic3d_TOD_VEC4)
488 {
489 for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
490 {
491 const Graphic3d_Vec3& aVert = *reinterpret_cast<const Graphic3d_Vec3* >(anAttribs->value (aVertIter) + anOffset);
492 aSet->Vertices.push_back (BVH_Vec4f (aVert.x(), aVert.y(), aVert.z(), 1.0f));
493 }
494 }
495 else if (anAttrib.DataType == Graphic3d_TOD_VEC2)
496 {
497 for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
498 {
499 const Graphic3d_Vec2& aVert = *reinterpret_cast<const Graphic3d_Vec2* >(anAttribs->value (aVertIter) + anOffset);
500 aSet->Vertices.push_back (BVH_Vec4f (aVert.x(), aVert.y(), 0.0f, 1.0f));
501 }
502 }
503 }
504 else if (anAttrib.Id == Graphic3d_TOA_NORM)
505 {
506 if (anAttrib.DataType == Graphic3d_TOD_VEC3
507 || anAttrib.DataType == Graphic3d_TOD_VEC4)
508 {
509 for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
510 {
511 const Graphic3d_Vec3& aNorm = *reinterpret_cast<const Graphic3d_Vec3* >(anAttribs->value (aVertIter) + anOffset);
512 aSet->Normals.push_back (BVH_Vec4f (aNorm.x(), aNorm.y(), aNorm.z(), 0.0f));
513 }
514 }
515 }
265d4508 516 }
e276548b 517
871fa103 518 if (aSet->Normals.size() != aSet->Vertices.size())
265d4508 519 {
871fa103 520 for (Standard_Integer aVertIter = 0; aVertIter < anAttribs->NbElements; ++aVertIter)
265d4508 521 {
871fa103 522 aSet->Normals.push_back (BVH_Vec4f());
265d4508 523 }
871fa103 524 }
e276548b 525
871fa103 526 if (theTransform)
527 {
528 for (size_t aVertIter = aVertFrom; aVertIter < aSet->Vertices.size(); ++aVertIter)
529 {
530 BVH_Vec4f& aVertex = aSet->Vertices[aVertIter];
531 aVertex = MatVecMult (theTransform, aVertex);
532 }
533 for (size_t aVertIter = aVertFrom; aVertIter < aSet->Normals.size(); ++aVertIter)
534 {
535 BVH_Vec4f& aNorm = aSet->Normals[aVertIter];
536 aNorm = MatVecMult (theTransform, aNorm);
537 }
e276548b 538 }
539
871fa103 540 if (!aBounds.IsNull())
265d4508 541 {
542 #ifdef RAY_TRACE_PRINT_INFO
bc8c79bb 543 std::cout << "\tNumber of bounds = " << aBounds->NbBounds << std::endl;
265d4508 544 #endif
e276548b 545
265d4508 546 Standard_Integer aBoundStart = 0;
871fa103 547 for (Standard_Integer aBound = 0; aBound < aBounds->NbBounds; ++aBound)
265d4508 548 {
871fa103 549 const Standard_Integer aVertNum = aBounds->Bounds[aBound];
e276548b 550
265d4508 551 #ifdef RAY_TRACE_PRINT_INFO
552 std::cout << "\tAdding indices from bound " << aBound << ": " <<
553 aBoundStart << " .. " << aVertNum << std::endl;
554 #endif
555
871fa103 556 if (!AddRaytraceVertexIndices (*aSet, *theArray, aBoundStart, aVertNum, theMatID))
265d4508 557 {
558 delete aSet;
559 return NULL;
560 }
561
562 aBoundStart += aVertNum;
563 }
564 }
565 else
e276548b 566 {
871fa103 567 const Standard_Integer aVertNum = !anIndices.IsNull() ? anIndices->NbElements : anAttribs->NbElements;
e276548b 568
265d4508 569 #ifdef RAY_TRACE_PRINT_INFO
570 std::cout << "\tAdding indices from array: " << aVertNum << std::endl;
571 #endif
e276548b 572
871fa103 573 if (!AddRaytraceVertexIndices (*aSet, *theArray, 0, aVertNum, theMatID))
e276548b 574 {
265d4508 575 delete aSet;
576 return NULL;
e276548b 577 }
e276548b 578 }
579 }
e276548b 580
265d4508 581 if (aSet->Size() != 0)
582 aSet->MarkDirty();
e276548b 583
265d4508 584 return aSet;
e276548b 585}
586
587// =======================================================================
588// function : AddRaytraceVertexIndices
589// purpose : Adds vertex indices to ray-traced scene geometry
590// =======================================================================
871fa103 591Standard_Boolean OpenGl_Workspace::AddRaytraceVertexIndices (OpenGl_TriangleSet& theSet,
592 const OpenGl_PrimitiveArray& theArray,
593 Standard_Integer theOffset,
594 Standard_Integer theCount,
595 Standard_Integer theMatID)
e276548b 596{
871fa103 597 switch (theArray.DrawMode())
e276548b 598 {
871fa103 599 case GL_TRIANGLES: return AddRaytraceTriangleArray (theSet, theArray.Indices(), theOffset, theCount, theMatID);
600 case GL_QUADS: return AddRaytraceQuadrangleArray (theSet, theArray.Indices(), theOffset, theCount, theMatID);
601 case GL_TRIANGLE_FAN: return AddRaytraceTriangleFanArray (theSet, theArray.Indices(), theOffset, theCount, theMatID);
602 case GL_TRIANGLE_STRIP: return AddRaytraceTriangleStripArray (theSet, theArray.Indices(), theOffset, theCount, theMatID);
603 case GL_QUAD_STRIP: return AddRaytraceQuadrangleStripArray (theSet, theArray.Indices(), theOffset, theCount, theMatID);
604 case GL_POLYGON: return AddRaytracePolygonArray (theSet, theArray.Indices(), theOffset, theCount, theMatID);
e276548b 605 }
871fa103 606 return Standard_False;
e276548b 607}
608
609// =======================================================================
610// function : AddRaytraceTriangleArray
611// purpose : Adds OpenGL triangle array to ray-traced scene geometry
612// =======================================================================
871fa103 613Standard_Boolean OpenGl_Workspace::AddRaytraceTriangleArray (OpenGl_TriangleSet& theSet,
614 const Handle(Graphic3d_IndexBuffer)& theIndices,
615 Standard_Integer theOffset,
616 Standard_Integer theCount,
617 Standard_Integer theMatID)
e276548b 618{
265d4508 619 if (theCount < 3)
e276548b 620 return Standard_True;
621
871fa103 622 theSet.Elements.reserve (theSet.Elements.size() + theCount / 3);
265d4508 623
871fa103 624 if (!theIndices.IsNull())
e276548b 625 {
265d4508 626 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; aVert += 3)
e276548b 627 {
871fa103 628 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0),
629 theIndices->Index (aVert + 1),
630 theIndices->Index (aVert + 2),
631 theMatID));
e276548b 632 }
633 }
634 else
635 {
265d4508 636 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; aVert += 3)
e276548b 637 {
871fa103 638 theSet.Elements.push_back (BVH_Vec4i (aVert + 0, aVert + 1, aVert + 2,
639 theMatID));
e276548b 640 }
641 }
642
643 return Standard_True;
644}
645
646// =======================================================================
647// function : AddRaytraceTriangleFanArray
648// purpose : Adds OpenGL triangle fan array to ray-traced scene geometry
649// =======================================================================
871fa103 650Standard_Boolean OpenGl_Workspace::AddRaytraceTriangleFanArray (OpenGl_TriangleSet& theSet,
651 const Handle(Graphic3d_IndexBuffer)& theIndices,
652 Standard_Integer theOffset,
653 Standard_Integer theCount,
654 Standard_Integer theMatID)
e276548b 655{
265d4508 656 if (theCount < 3)
e276548b 657 return Standard_True;
658
871fa103 659 theSet.Elements.reserve (theSet.Elements.size() + theCount - 2);
265d4508 660
871fa103 661 if (!theIndices.IsNull())
e276548b 662 {
265d4508 663 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
e276548b 664 {
871fa103 665 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (theOffset),
666 theIndices->Index (aVert + 1),
667 theIndices->Index (aVert + 2),
668 theMatID));
e276548b 669 }
670 }
671 else
672 {
265d4508 673 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
e276548b 674 {
871fa103 675 theSet.Elements.push_back (BVH_Vec4i (theOffset,
676 aVert + 1,
677 aVert + 2,
678 theMatID));
e276548b 679 }
680 }
681
682 return Standard_True;
683}
684
685// =======================================================================
686// function : AddRaytraceTriangleStripArray
687// purpose : Adds OpenGL triangle strip array to ray-traced scene geometry
688// =======================================================================
871fa103 689Standard_Boolean OpenGl_Workspace::AddRaytraceTriangleStripArray (OpenGl_TriangleSet& theSet,
690 const Handle(Graphic3d_IndexBuffer)& theIndices,
691 Standard_Integer theOffset,
692 Standard_Integer theCount,
693 Standard_Integer theMatID)
e276548b 694{
265d4508 695 if (theCount < 3)
e276548b 696 return Standard_True;
697
871fa103 698 theSet.Elements.reserve (theSet.Elements.size() + theCount - 2);
265d4508 699
871fa103 700 if (!theIndices.IsNull())
e276548b 701 {
265d4508 702 for (Standard_Integer aVert = theOffset, aCW = 0; aVert < theOffset + theCount - 2; ++aVert, aCW = (aCW + 1) % 2)
e276548b 703 {
871fa103 704 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + aCW ? 1 : 0),
705 theIndices->Index (aVert + aCW ? 0 : 1),
706 theIndices->Index (aVert + 2),
707 theMatID));
e276548b 708 }
709 }
710 else
711 {
265d4508 712 for (Standard_Integer aVert = theOffset, aCW = 0; aVert < theOffset + theCount - 2; ++aVert, aCW = (aCW + 1) % 2)
e276548b 713 {
871fa103 714 theSet.Elements.push_back (BVH_Vec4i (aVert + aCW ? 1 : 0,
715 aVert + aCW ? 0 : 1,
716 aVert + 2,
717 theMatID));
e276548b 718 }
719 }
720
721 return Standard_True;
722}
723
724// =======================================================================
725// function : AddRaytraceQuadrangleArray
726// purpose : Adds OpenGL quad array to ray-traced scene geometry
727// =======================================================================
871fa103 728Standard_Boolean OpenGl_Workspace::AddRaytraceQuadrangleArray (OpenGl_TriangleSet& theSet,
729 const Handle(Graphic3d_IndexBuffer)& theIndices,
730 Standard_Integer theOffset,
731 Standard_Integer theCount,
732 Standard_Integer theMatID)
e276548b 733{
265d4508 734 if (theCount < 4)
e276548b 735 return Standard_True;
736
871fa103 737 theSet.Elements.reserve (theSet.Elements.size() + theCount / 2);
265d4508 738
871fa103 739 if (!theIndices.IsNull())
e276548b 740 {
265d4508 741 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 4)
e276548b 742 {
871fa103 743 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0),
744 theIndices->Index (aVert + 1),
745 theIndices->Index (aVert + 2),
746 theMatID));
747 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0),
748 theIndices->Index (aVert + 2),
749 theIndices->Index (aVert + 3),
750 theMatID));
e276548b 751 }
752 }
753 else
754 {
265d4508 755 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 4)
e276548b 756 {
871fa103 757 theSet.Elements.push_back (BVH_Vec4i (aVert + 0, aVert + 1, aVert + 2,
758 theMatID));
759 theSet.Elements.push_back (BVH_Vec4i (aVert + 0, aVert + 2, aVert + 3,
760 theMatID));
e276548b 761 }
762 }
763
764 return Standard_True;
765}
766
767// =======================================================================
768// function : AddRaytraceQuadrangleStripArray
769// purpose : Adds OpenGL quad strip array to ray-traced scene geometry
770// =======================================================================
871fa103 771Standard_Boolean OpenGl_Workspace::AddRaytraceQuadrangleStripArray (OpenGl_TriangleSet& theSet,
772 const Handle(Graphic3d_IndexBuffer)& theIndices,
773 Standard_Integer theOffset,
774 Standard_Integer theCount,
775 Standard_Integer theMatID)
e276548b 776{
265d4508 777 if (theCount < 4)
e276548b 778 return Standard_True;
779
871fa103 780 theSet.Elements.reserve (theSet.Elements.size() + 2 * theCount - 6);
265d4508 781
871fa103 782 if (!theIndices.IsNull())
e276548b 783 {
265d4508 784 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 2)
e276548b 785 {
871fa103 786 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 0),
787 theIndices->Index (aVert + 1),
788 theIndices->Index (aVert + 2),
789 theMatID));
790
791 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (aVert + 1),
792 theIndices->Index (aVert + 3),
793 theIndices->Index (aVert + 2),
794 theMatID));
e276548b 795 }
796 }
797 else
798 {
265d4508 799 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 3; aVert += 2)
e276548b 800 {
871fa103 801 theSet.Elements.push_back (BVH_Vec4i (aVert + 0,
802 aVert + 1,
803 aVert + 2,
804 theMatID));
805
806 theSet.Elements.push_back (BVH_Vec4i (aVert + 1,
807 aVert + 3,
808 aVert + 2,
809 theMatID));
e276548b 810 }
811 }
812
813 return Standard_True;
814}
815
816// =======================================================================
817// function : AddRaytracePolygonArray
818// purpose : Adds OpenGL polygon array to ray-traced scene geometry
819// =======================================================================
871fa103 820Standard_Boolean OpenGl_Workspace::AddRaytracePolygonArray (OpenGl_TriangleSet& theSet,
821 const Handle(Graphic3d_IndexBuffer)& theIndices,
822 Standard_Integer theOffset,
823 Standard_Integer theCount,
824 Standard_Integer theMatID)
e276548b 825{
265d4508 826 if (theCount < 3)
e276548b 827 return Standard_True;
828
871fa103 829 theSet.Elements.reserve (theSet.Elements.size() + theCount - 2);
265d4508 830
871fa103 831 if (!theIndices.IsNull())
e276548b 832 {
265d4508 833 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
e276548b 834 {
871fa103 835 theSet.Elements.push_back (BVH_Vec4i (theIndices->Index (theOffset),
836 theIndices->Index (aVert + 1),
837 theIndices->Index (aVert + 2),
838 theMatID));
e276548b 839 }
840 }
841 else
842 {
265d4508 843 for (Standard_Integer aVert = theOffset; aVert < theOffset + theCount - 2; ++aVert)
e276548b 844 {
871fa103 845 theSet.Elements.push_back (BVH_Vec4i (theOffset,
846 aVert + 1,
847 aVert + 2,
848 theMatID));
e276548b 849 }
850 }
851
852 return Standard_True;
853}
854
855// =======================================================================
856// function : UpdateRaytraceLightSources
857// purpose : Updates 3D scene light sources for ray-tracing
858// =======================================================================
859Standard_Boolean OpenGl_Workspace::UpdateRaytraceLightSources (const GLdouble theInvModelView[16])
860{
265d4508 861 myRaytraceGeometry.Sources.clear();
e276548b 862
fc73a202 863 myRaytraceGeometry.Ambient = BVH_Vec4f (0.0f, 0.0f, 0.0f, 0.0f);
265d4508 864
865 for (OpenGl_ListOfLight::Iterator anItl (myView->LightList()); anItl.More(); anItl.Next())
e276548b 866 {
12381341 867 const OpenGl_Light& aLight = anItl.Value();
265d4508 868
12381341 869 if (aLight.Type == Visual3d_TOLS_AMBIENT)
e276548b 870 {
fc73a202 871 myRaytraceGeometry.Ambient += BVH_Vec4f (aLight.Color.r(),
872 aLight.Color.g(),
873 aLight.Color.b(),
874 0.0f);
e276548b 875 continue;
876 }
877
265d4508 878 BVH_Vec4f aDiffuse (aLight.Color.r(),
879 aLight.Color.g(),
880 aLight.Color.b(),
881 1.0f);
882
883 BVH_Vec4f aPosition (-aLight.Direction.x(),
884 -aLight.Direction.y(),
885 -aLight.Direction.z(),
886 0.0f);
887
12381341 888 if (aLight.Type != Visual3d_TOLS_DIRECTIONAL)
e276548b 889 {
265d4508 890 aPosition = BVH_Vec4f (aLight.Position.x(),
891 aLight.Position.y(),
892 aLight.Position.z(),
893 1.0f);
e276548b 894 }
265d4508 895
12381341 896 if (aLight.IsHeadlight)
e276548b 897 aPosition = MatVecMult (theInvModelView, aPosition);
e276548b 898
fc73a202 899
265d4508 900 myRaytraceGeometry.Sources.push_back (OpenGl_RaytraceLight (aDiffuse, aPosition));
e276548b 901 }
902
fc73a202 903 if (myRaytraceLightSrcTexture.IsNull()) // create light source buffer
e276548b 904 {
fc73a202 905 myRaytraceLightSrcTexture = new OpenGl_TextureBufferArb;
e276548b 906
fc73a202 907 if (!myRaytraceLightSrcTexture->Create (myGlContext))
908 {
e276548b 909#ifdef RAY_TRACE_PRINT_INFO
fc73a202 910 std::cout << "Error: Failed to create light source buffer" << std::endl;
e276548b 911#endif
fc73a202 912 return Standard_False;
913 }
e276548b 914 }
fc73a202 915
916 if (myRaytraceGeometry.Sources.size() != 0)
e276548b 917 {
fc73a202 918 const GLfloat* aDataPtr = myRaytraceGeometry.Sources.front().Packed();
5cff985a 919 if (!myRaytraceLightSrcTexture->Init (myGlContext, 4, GLsizei (myRaytraceGeometry.Sources.size() * 2), aDataPtr))
fc73a202 920 {
921#ifdef RAY_TRACE_PRINT_INFO
922 std::cout << "Error: Failed to upload light source buffer" << std::endl;
e276548b 923#endif
fc73a202 924 return Standard_False;
925 }
926 }
e276548b 927
928 return Standard_True;
929}
930
931// =======================================================================
fc73a202 932// function : UpdateRaytraceEnvironmentMap
933// purpose : Updates environment map for ray-tracing
e276548b 934// =======================================================================
fc73a202 935Standard_Boolean OpenGl_Workspace::UpdateRaytraceEnvironmentMap()
e276548b 936{
fc73a202 937 if (myView.IsNull())
e276548b 938 return Standard_False;
e276548b 939
fc73a202 940 if (myViewModificationStatus == myView->ModificationState())
941 return Standard_True;
e276548b 942
fc73a202 943 for (Standard_Integer anIdx = 0; anIdx < 2; ++anIdx)
e276548b 944 {
fc73a202 945 const Handle(OpenGl_ShaderProgram)& aProgram =
946 anIdx == 0 ? myRaytraceProgram : myPostFSAAProgram;
e276548b 947
fc73a202 948 if (!aProgram.IsNull())
e276548b 949 {
7d3e64ef 950 myGlContext->BindProgram (aProgram);
e276548b 951
fc73a202 952 if (!myView->TextureEnv().IsNull() && myView->SurfaceDetail() != Visual3d_TOD_NONE)
e276548b 953 {
fc73a202 954 myView->TextureEnv()->Bind (
955 myGlContext, GL_TEXTURE0 + OpenGl_RT_EnvironmentMapTexture);
956
84c71f29 957 aProgram->SetUniform (myGlContext,
958 myUniformLocations[anIdx][OpenGl_RT_uEnvironmentEnable], 1);
e276548b 959 }
960 else
961 {
84c71f29 962 aProgram->SetUniform (myGlContext,
963 myUniformLocations[anIdx][OpenGl_RT_uEnvironmentEnable], 0);
e276548b 964 }
fc73a202 965 }
e276548b 966 }
967
7d3e64ef 968 myGlContext->BindProgram (NULL);
fc73a202 969 myViewModificationStatus = myView->ModificationState();
e276548b 970 return Standard_True;
971}
972
973// =======================================================================
fc73a202 974// function : Source
975// purpose : Returns shader source combined with prefix
e276548b 976// =======================================================================
fc73a202 977TCollection_AsciiString OpenGl_Workspace::ShaderSource::Source() const
e276548b 978{
fc73a202 979 static const TCollection_AsciiString aVersion = "#version 140";
e276548b 980
fc73a202 981 if (myPrefix.IsEmpty())
e276548b 982 {
fc73a202 983 return aVersion + "\n" + mySource;
e276548b 984 }
985
fc73a202 986 return aVersion + "\n" + myPrefix + "\n" + mySource;
e276548b 987}
988
989// =======================================================================
fc73a202 990// function : Load
991// purpose : Loads shader source from specified files
e276548b 992// =======================================================================
fc73a202 993void OpenGl_Workspace::ShaderSource::Load (
994 const TCollection_AsciiString* theFileNames, const Standard_Integer theCount)
e276548b 995{
fc73a202 996 mySource.Clear();
e276548b 997
fc73a202 998 for (Standard_Integer anIndex = 0; anIndex < theCount; ++anIndex)
999 {
1000 OSD_File aFile (theFileNames[anIndex]);
e276548b 1001
fc73a202 1002 Standard_ASSERT_RETURN (aFile.Exists(),
1003 "Error: Failed to find shader source file", /* none */);
e276548b 1004
fc73a202 1005 aFile.Open (OSD_ReadOnly, OSD_Protection());
265d4508 1006
fc73a202 1007 TCollection_AsciiString aSource;
265d4508 1008
fc73a202 1009 Standard_ASSERT_RETURN (aFile.IsOpen(),
1010 "Error: Failed to open shader source file", /* none */);
e276548b 1011
fc73a202 1012 aFile.Read (aSource, (Standard_Integer) aFile.Size());
e276548b 1013
fc73a202 1014 if (!aSource.IsEmpty())
1015 {
1016 mySource += TCollection_AsciiString ("\n") + aSource;
1017 }
68333c8f 1018
fc73a202 1019 aFile.Close();
68333c8f 1020 }
e276548b 1021}
1022
1023// =======================================================================
fc73a202 1024// function : LoadShader
1025// purpose : Creates new shader object with specified source
e276548b 1026// =======================================================================
fc73a202 1027Handle(OpenGl_ShaderObject) OpenGl_Workspace::LoadShader (const ShaderSource& theSource, GLenum theType)
e276548b 1028{
fc73a202 1029 Handle(OpenGl_ShaderObject) aShader = new OpenGl_ShaderObject (theType);
e276548b 1030
fc73a202 1031 if (!aShader->Create (myGlContext))
e276548b 1032 {
fc73a202 1033 const TCollection_ExtendedString aMessage = "Error: Failed to create shader object";
1034
1035 myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
1036 GL_DEBUG_TYPE_ERROR_ARB, 0, GL_DEBUG_SEVERITY_HIGH_ARB, aMessage);
e276548b 1037
fc73a202 1038 aShader->Release (myGlContext.operator->());
e276548b 1039
fc73a202 1040 return Handle(OpenGl_ShaderObject)();
e276548b 1041 }
5322131b 1042
fc73a202 1043 if (!aShader->LoadSource (myGlContext, theSource.Source()))
1044 {
1045 const TCollection_ExtendedString aMessage = "Error: Failed to set shader source";
1046
1047 myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
1048 GL_DEBUG_TYPE_ERROR_ARB, 0, GL_DEBUG_SEVERITY_HIGH_ARB, aMessage);
e276548b 1049
fc73a202 1050 aShader->Release (myGlContext.operator->());
e276548b 1051
fc73a202 1052 return Handle(OpenGl_ShaderObject)();
1053 }
e276548b 1054
fc73a202 1055 TCollection_AsciiString aBuildLog;
e276548b 1056
fc73a202 1057 if (!aShader->Compile (myGlContext))
e276548b 1058 {
fc73a202 1059 if (aShader->FetchInfoLog (myGlContext, aBuildLog))
1060 {
1061 const TCollection_ExtendedString aMessage =
1062 TCollection_ExtendedString ("Error: Failed to compile shader object:\n") + aBuildLog;
1063
e276548b 1064#ifdef RAY_TRACE_PRINT_INFO
fc73a202 1065 std::cout << aBuildLog << std::endl;
e276548b 1066#endif
e276548b 1067
fc73a202 1068 myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
1069 GL_DEBUG_TYPE_ERROR_ARB, 0, GL_DEBUG_SEVERITY_HIGH_ARB, aMessage);
1070 }
1071
1072 aShader->Release (myGlContext.operator->());
1073
1074 return Handle(OpenGl_ShaderObject)();
1075 }
68333c8f 1076
e276548b 1077#ifdef RAY_TRACE_PRINT_INFO
fc73a202 1078 if (aShader->FetchInfoLog (myGlContext, aBuildLog))
1079 {
1080 if (!aBuildLog.IsEmpty())
1081 {
1082 std::cout << aBuildLog << std::endl;
1083 }
1084 else
1085 {
1086 std::cout << "Info: shader build log is empty" << std::endl;
1087 }
1088 }
e276548b 1089#endif
e276548b 1090
fc73a202 1091 return aShader;
e276548b 1092}
1093
1094// =======================================================================
fc73a202 1095// function : SafeFailBack
1096// purpose : Performs safe exit when shaders initialization fails
e276548b 1097// =======================================================================
fc73a202 1098Standard_Boolean OpenGl_Workspace::SafeFailBack (const TCollection_ExtendedString& theMessage)
e276548b 1099{
fc73a202 1100 myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
1101 GL_DEBUG_TYPE_ERROR_ARB, 0, GL_DEBUG_SEVERITY_HIGH_ARB, theMessage);
265d4508 1102
fc73a202 1103 myComputeInitStatus = OpenGl_RT_FAIL;
265d4508 1104
fc73a202 1105 ReleaseRaytraceResources();
1106
1107 return Standard_False;
1108}
e276548b 1109
fc73a202 1110// =======================================================================
1111// function : InitRaytraceResources
1112// purpose : Initializes OpenGL/GLSL shader programs
1113// =======================================================================
bc8c79bb 1114Standard_Boolean OpenGl_Workspace::InitRaytraceResources (const Graphic3d_CView& theCView)
fc73a202 1115{
1116 Standard_Boolean aToRebuildShaders = Standard_False;
e276548b 1117
fc73a202 1118 if (myComputeInitStatus == OpenGl_RT_INIT)
1119 {
1120 if (!myIsRaytraceDataValid)
1121 return Standard_True;
e276548b 1122
fc73a202 1123 const Standard_Integer aRequiredStackSize =
1124 myRaytraceGeometry.HighLevelTreeDepth() + myRaytraceGeometry.BottomLevelTreeDepth();
e276548b 1125
bc8c79bb 1126 if (myRaytraceParameters.StackSize < aRequiredStackSize)
fc73a202 1127 {
bc8c79bb 1128 myRaytraceParameters.StackSize = Max (aRequiredStackSize, THE_DEFAULT_STACK_SIZE);
e276548b 1129
fc73a202 1130 aToRebuildShaders = Standard_True;
1131 }
1132 else
1133 {
bc8c79bb 1134 if (aRequiredStackSize < myRaytraceParameters.StackSize)
fc73a202 1135 {
bc8c79bb 1136 if (myRaytraceParameters.StackSize > THE_DEFAULT_STACK_SIZE)
fc73a202 1137 {
bc8c79bb 1138 myRaytraceParameters.StackSize = Max (aRequiredStackSize, THE_DEFAULT_STACK_SIZE);
fc73a202 1139 aToRebuildShaders = Standard_True;
1140 }
1141 }
1142 }
e276548b 1143
bc8c79bb 1144 if (theCView.RenderParams.RaytracingDepth != myRaytraceParameters.TraceDepth)
1145 {
1146 myRaytraceParameters.TraceDepth = theCView.RenderParams.RaytracingDepth;
1147 aToRebuildShaders = Standard_True;
1148 }
1149
1150 if (theCView.RenderParams.IsTransparentShadowEnabled != myRaytraceParameters.TransparentShadows)
1151 {
1152 myRaytraceParameters.TransparentShadows = theCView.RenderParams.IsTransparentShadowEnabled;
1153 aToRebuildShaders = Standard_True;
1154 }
1155
fc73a202 1156 if (aToRebuildShaders)
1157 {
e276548b 1158#ifdef RAY_TRACE_PRINT_INFO
bc8c79bb 1159 std::cout << "Info: Rebuild shaders with stack size: " << myRaytraceParameters.StackSize << std::endl;
e276548b 1160#endif
e276548b 1161
bc8c79bb 1162 // Change state to force update all uniforms
84c71f29 1163 ++myViewModificationStatus;
1164
bc8c79bb 1165 TCollection_AsciiString aPrefixString =
1166 TCollection_AsciiString ("#define STACK_SIZE ") + TCollection_AsciiString (myRaytraceParameters.StackSize) + "\n" +
1167 TCollection_AsciiString ("#define TRACE_DEPTH ") + TCollection_AsciiString (myRaytraceParameters.TraceDepth);
1168
1169 if (myRaytraceParameters.TransparentShadows)
1170 {
1171 aPrefixString += TCollection_AsciiString ("\n#define TRANSPARENT_SHADOWS");
1172 }
1173
1174#ifdef RAY_TRACE_PRINT_INFO
1175 std::cout << "GLSL prefix string:" << std::endl << aPrefixString << std::endl;
1176#endif
265d4508 1177
bc8c79bb 1178 myRaytraceShaderSource.SetPrefix (aPrefixString);
1179 myPostFSAAShaderSource.SetPrefix (aPrefixString);
265d4508 1180
fc73a202 1181 if (!myRaytraceShader->LoadSource (myGlContext, myRaytraceShaderSource.Source())
1182 || !myPostFSAAShader->LoadSource (myGlContext, myPostFSAAShaderSource.Source()))
1183 {
1184 return Standard_False;
1185 }
265d4508 1186
fc73a202 1187 if (!myRaytraceShader->Compile (myGlContext)
1188 || !myPostFSAAShader->Compile (myGlContext))
1189 {
1190 return Standard_False;
1191 }
1192
7d3e64ef 1193 myRaytraceProgram->SetAttributeName (myGlContext, Graphic3d_TOA_POS, "occVertex");
1194 myPostFSAAProgram->SetAttributeName (myGlContext, Graphic3d_TOA_POS, "occVertex");
fc73a202 1195 if (!myRaytraceProgram->Link (myGlContext)
1196 || !myPostFSAAProgram->Link (myGlContext))
1197 {
1198 return Standard_False;
1199 }
1200 }
e276548b 1201 }
1202
fc73a202 1203 if (myComputeInitStatus == OpenGl_RT_NONE)
1204 {
1205 if (!myGlContext->IsGlGreaterEqual (3, 1))
1206 {
1207 const TCollection_ExtendedString aMessage = "Ray-tracing requires OpenGL 3.1 and higher";
265d4508 1208
fc73a202 1209 myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
1210 GL_DEBUG_TYPE_ERROR_ARB, 0, GL_DEBUG_SEVERITY_HIGH_ARB, aMessage);
265d4508 1211
fc73a202 1212 return Standard_False;
1213 }
5322131b 1214
bc8c79bb 1215 myRaytraceParameters.TraceDepth = theCView.RenderParams.RaytracingDepth;
1216
fc73a202 1217 TCollection_AsciiString aFolder = Graphic3d_ShaderProgram::ShadersFolder();
265d4508 1218
fc73a202 1219 if (aFolder.IsEmpty())
1220 {
1221 const TCollection_ExtendedString aMessage = "Failed to locate shaders directory";
1222
1223 myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
1224 GL_DEBUG_TYPE_ERROR_ARB, 0, GL_DEBUG_SEVERITY_HIGH_ARB, aMessage);
1225
1226 return Standard_False;
1227 }
265d4508 1228
fc73a202 1229 if (myIsRaytraceDataValid)
1230 {
bc8c79bb 1231 myRaytraceParameters.StackSize = Max (THE_DEFAULT_STACK_SIZE,
fc73a202 1232 myRaytraceGeometry.HighLevelTreeDepth() + myRaytraceGeometry.BottomLevelTreeDepth());
1233 }
265d4508 1234
bc8c79bb 1235 TCollection_AsciiString aPrefixString =
1236 TCollection_AsciiString ("#define STACK_SIZE ") + TCollection_AsciiString (myRaytraceParameters.StackSize) + "\n" +
1237 TCollection_AsciiString ("#define TRACE_DEPTH ") + TCollection_AsciiString (myRaytraceParameters.TraceDepth);
1238
1239 if (myRaytraceParameters.TransparentShadows)
1240 {
1241 aPrefixString += TCollection_AsciiString ("\n#define TRANSPARENT_SHADOWS");
1242 }
1243
1244#ifdef RAY_TRACE_PRINT_INFO
1245 std::cout << "GLSL prefix string:" << std::endl << aPrefixString << std::endl;
1246#endif
1247
fc73a202 1248 {
1249 Handle(OpenGl_ShaderObject) aBasicVertShader = LoadShader (
1250 ShaderSource (aFolder + "/RaytraceBase.vs"), GL_VERTEX_SHADER);
265d4508 1251
fc73a202 1252 if (aBasicVertShader.IsNull())
1253 {
1254 return SafeFailBack ("Failed to set vertex shader source");
1255 }
265d4508 1256
fc73a202 1257 TCollection_AsciiString aFiles[] = { aFolder + "/RaytraceBase.fs", aFolder + "/RaytraceRender.fs" };
265d4508 1258
fc73a202 1259 myRaytraceShaderSource.Load (aFiles, 2);
e276548b 1260
bc8c79bb 1261 myRaytraceShaderSource.SetPrefix (aPrefixString);
265d4508 1262
fc73a202 1263 myRaytraceShader = LoadShader (myRaytraceShaderSource, GL_FRAGMENT_SHADER);
265d4508 1264
fc73a202 1265 if (myRaytraceShader.IsNull())
1266 {
1267 aBasicVertShader->Release (myGlContext.operator->());
265d4508 1268
fc73a202 1269 return SafeFailBack ("Failed to set ray-trace fragment shader source");
1270 }
265d4508 1271
fc73a202 1272 myRaytraceProgram = new OpenGl_ShaderProgram;
5322131b 1273
fc73a202 1274 if (!myRaytraceProgram->Create (myGlContext))
1275 {
1276 aBasicVertShader->Release (myGlContext.operator->());
265d4508 1277
fc73a202 1278 return SafeFailBack ("Failed to create ray-trace shader program");
1279 }
265d4508 1280
fc73a202 1281 if (!myRaytraceProgram->AttachShader (myGlContext, aBasicVertShader)
1282 || !myRaytraceProgram->AttachShader (myGlContext, myRaytraceShader))
1283 {
1284 aBasicVertShader->Release (myGlContext.operator->());
265d4508 1285
fc73a202 1286 return SafeFailBack ("Failed to attach ray-trace shader objects");
1287 }
265d4508 1288
7d3e64ef 1289 myRaytraceProgram->SetAttributeName (myGlContext, Graphic3d_TOA_POS, "occVertex");
fc73a202 1290 if (!myRaytraceProgram->Link (myGlContext))
1291 {
1292 TCollection_AsciiString aLinkLog;
e276548b 1293
fc73a202 1294 if (myRaytraceProgram->FetchInfoLog (myGlContext, aLinkLog))
1295 {
1296 #ifdef RAY_TRACE_PRINT_INFO
1297 std::cout << aLinkLog << std::endl;
1298 #endif
1299 }
265d4508 1300
fc73a202 1301 return SafeFailBack ("Failed to link ray-trace shader program");
1302 }
1303 }
265d4508 1304
fc73a202 1305 {
1306 Handle(OpenGl_ShaderObject) aBasicVertShader = LoadShader (
1307 ShaderSource (aFolder + "/RaytraceBase.vs"), GL_VERTEX_SHADER);
265d4508 1308
fc73a202 1309 if (aBasicVertShader.IsNull())
1310 {
1311 return SafeFailBack ("Failed to set vertex shader source");
1312 }
265d4508 1313
fc73a202 1314 TCollection_AsciiString aFiles[] = { aFolder + "/RaytraceBase.fs", aFolder + "/RaytraceSmooth.fs" };
265d4508 1315
fc73a202 1316 myPostFSAAShaderSource.Load (aFiles, 2);
265d4508 1317
bc8c79bb 1318 myPostFSAAShaderSource.SetPrefix (aPrefixString);
fc73a202 1319
1320 myPostFSAAShader = LoadShader (myPostFSAAShaderSource, GL_FRAGMENT_SHADER);
265d4508 1321
fc73a202 1322 if (myPostFSAAShader.IsNull())
1323 {
1324 aBasicVertShader->Release (myGlContext.operator->());
265d4508 1325
fc73a202 1326 return SafeFailBack ("Failed to set FSAA fragment shader source");
1327 }
265d4508 1328
fc73a202 1329 myPostFSAAProgram = new OpenGl_ShaderProgram;
265d4508 1330
fc73a202 1331 if (!myPostFSAAProgram->Create (myGlContext))
1332 {
1333 aBasicVertShader->Release (myGlContext.operator->());
265d4508 1334
fc73a202 1335 return SafeFailBack ("Failed to create FSAA shader program");
1336 }
1337
1338 if (!myPostFSAAProgram->AttachShader (myGlContext, aBasicVertShader)
1339 || !myPostFSAAProgram->AttachShader (myGlContext, myPostFSAAShader))
1340 {
1341 aBasicVertShader->Release (myGlContext.operator->());
1342
1343 return SafeFailBack ("Failed to attach FSAA shader objects");
1344 }
1345
7d3e64ef 1346 myPostFSAAProgram->SetAttributeName (myGlContext, Graphic3d_TOA_POS, "occVertex");
fc73a202 1347 if (!myPostFSAAProgram->Link (myGlContext))
1348 {
1349 TCollection_AsciiString aLinkLog;
1350
1351 if (myPostFSAAProgram->FetchInfoLog (myGlContext, aLinkLog))
1352 {
1353 #ifdef RAY_TRACE_PRINT_INFO
1354 std::cout << aLinkLog << std::endl;
1355 #endif
1356 }
1357
1358 return SafeFailBack ("Failed to link FSAA shader program");
1359 }
e276548b 1360 }
fc73a202 1361 }
e276548b 1362
fc73a202 1363 if (myComputeInitStatus == OpenGl_RT_NONE || aToRebuildShaders)
1364 {
1365 for (Standard_Integer anIndex = 0; anIndex < 2; ++anIndex)
e276548b 1366 {
fc73a202 1367 Handle(OpenGl_ShaderProgram)& aShaderProgram =
1368 (anIndex == 0) ? myRaytraceProgram : myPostFSAAProgram;
1369
7d3e64ef 1370 myGlContext->BindProgram (aShaderProgram);
fc73a202 1371
1372 aShaderProgram->SetSampler (myGlContext,
1373 "uSceneMinPointTexture", OpenGl_RT_SceneMinPointTexture);
1374 aShaderProgram->SetSampler (myGlContext,
1375 "uSceneMaxPointTexture", OpenGl_RT_SceneMaxPointTexture);
1376 aShaderProgram->SetSampler (myGlContext,
1377 "uSceneNodeInfoTexture", OpenGl_RT_SceneNodeInfoTexture);
1378 aShaderProgram->SetSampler (myGlContext,
1379 "uObjectMinPointTexture", OpenGl_RT_ObjectMinPointTexture);
1380 aShaderProgram->SetSampler (myGlContext,
1381 "uObjectMaxPointTexture", OpenGl_RT_ObjectMaxPointTexture);
1382 aShaderProgram->SetSampler (myGlContext,
1383 "uObjectNodeInfoTexture", OpenGl_RT_ObjectNodeInfoTexture);
1384 aShaderProgram->SetSampler (myGlContext,
1385 "uGeometryVertexTexture", OpenGl_RT_GeometryVertexTexture);
1386 aShaderProgram->SetSampler (myGlContext,
1387 "uGeometryNormalTexture", OpenGl_RT_GeometryNormalTexture);
1388 aShaderProgram->SetSampler (myGlContext,
1389 "uGeometryTriangTexture", OpenGl_RT_GeometryTriangTexture);
1390 aShaderProgram->SetSampler (myGlContext,
1391 "uRaytraceMaterialTexture", OpenGl_RT_RaytraceMaterialTexture);
1392 aShaderProgram->SetSampler (myGlContext,
1393 "uRaytraceLightSrcTexture", OpenGl_RT_RaytraceLightSrcTexture);
84c71f29 1394 aShaderProgram->SetSampler (myGlContext,
1395 "uSceneTransformTexture", OpenGl_RT_SceneTransformTexture);
1396 aShaderProgram->SetSampler (myGlContext,
1397 "uEnvironmentMapTexture", OpenGl_RT_EnvironmentMapTexture);
fc73a202 1398
a89742cf 1399 aShaderProgram->SetSampler (myGlContext,
1400 "uOpenGlColorTexture", OpenGl_RT_OpenGlColorTexture);
1401 aShaderProgram->SetSampler (myGlContext,
1402 "uOpenGlDepthTexture", OpenGl_RT_OpenGlDepthTexture);
1403
fc73a202 1404 if (anIndex == 1)
1405 {
1406 aShaderProgram->SetSampler (myGlContext,
1407 "uFSAAInputTexture", OpenGl_RT_FSAAInputTexture);
1408 }
265d4508 1409
fc73a202 1410 myUniformLocations[anIndex][OpenGl_RT_aPosition] =
7d3e64ef 1411 aShaderProgram->GetAttributeLocation (myGlContext, "occVertex");
fc73a202 1412
1413 myUniformLocations[anIndex][OpenGl_RT_uOriginLB] =
1414 aShaderProgram->GetUniformLocation (myGlContext, "uOriginLB");
1415 myUniformLocations[anIndex][OpenGl_RT_uOriginRB] =
1416 aShaderProgram->GetUniformLocation (myGlContext, "uOriginRB");
1417 myUniformLocations[anIndex][OpenGl_RT_uOriginLT] =
1418 aShaderProgram->GetUniformLocation (myGlContext, "uOriginLT");
1419 myUniformLocations[anIndex][OpenGl_RT_uOriginRT] =
1420 aShaderProgram->GetUniformLocation (myGlContext, "uOriginRT");
1421 myUniformLocations[anIndex][OpenGl_RT_uDirectLB] =
1422 aShaderProgram->GetUniformLocation (myGlContext, "uDirectLB");
1423 myUniformLocations[anIndex][OpenGl_RT_uDirectRB] =
1424 aShaderProgram->GetUniformLocation (myGlContext, "uDirectRB");
1425 myUniformLocations[anIndex][OpenGl_RT_uDirectLT] =
1426 aShaderProgram->GetUniformLocation (myGlContext, "uDirectLT");
1427 myUniformLocations[anIndex][OpenGl_RT_uDirectRT] =
1428 aShaderProgram->GetUniformLocation (myGlContext, "uDirectRT");
a89742cf 1429 myUniformLocations[anIndex][OpenGl_RT_uInvModelProj] =
1430 aShaderProgram->GetUniformLocation (myGlContext, "uInvModelProj");
fc73a202 1431
1432 myUniformLocations[anIndex][OpenGl_RT_uLightCount] =
1433 aShaderProgram->GetUniformLocation (myGlContext, "uLightCount");
1434 myUniformLocations[anIndex][OpenGl_RT_uLightAmbnt] =
1435 aShaderProgram->GetUniformLocation (myGlContext, "uGlobalAmbient");
1436
1437 myUniformLocations[anIndex][OpenGl_RT_uSceneRad] =
1438 aShaderProgram->GetUniformLocation (myGlContext, "uSceneRadius");
1439 myUniformLocations[anIndex][OpenGl_RT_uSceneEps] =
1440 aShaderProgram->GetUniformLocation (myGlContext, "uSceneEpsilon");
1441
1442 myUniformLocations[anIndex][OpenGl_RT_uShadEnabled] =
1443 aShaderProgram->GetUniformLocation (myGlContext, "uShadowsEnable");
1444 myUniformLocations[anIndex][OpenGl_RT_uReflEnabled] =
1445 aShaderProgram->GetUniformLocation (myGlContext, "uReflectionsEnable");
1446
1447 myUniformLocations[anIndex][OpenGl_RT_uOffsetX] =
1448 aShaderProgram->GetUniformLocation (myGlContext, "uOffsetX");
1449 myUniformLocations[anIndex][OpenGl_RT_uOffsetY] =
1450 aShaderProgram->GetUniformLocation (myGlContext, "uOffsetY");
1451 myUniformLocations[anIndex][OpenGl_RT_uSamples] =
1452 aShaderProgram->GetUniformLocation (myGlContext, "uSamples");
84c71f29 1453
1454 myUniformLocations[anIndex][OpenGl_RT_uEnvironmentEnable] =
1455 aShaderProgram->GetUniformLocation (myGlContext, "uEnvironmentEnable");
fc73a202 1456 }
265d4508 1457
7d3e64ef 1458 myGlContext->BindProgram (NULL);
fc73a202 1459 }
265d4508 1460
fc73a202 1461 if (myComputeInitStatus != OpenGl_RT_NONE)
1462 {
1463 return myComputeInitStatus == OpenGl_RT_INIT;
1464 }
265d4508 1465
fc73a202 1466 if (myRaytraceFBO1.IsNull())
1467 {
1468 myRaytraceFBO1 = new OpenGl_FrameBuffer;
1469 }
265d4508 1470
fc73a202 1471 if (myRaytraceFBO2.IsNull())
1472 {
1473 myRaytraceFBO2 = new OpenGl_FrameBuffer;
1474 }
265d4508 1475
fc73a202 1476 const GLfloat aVertices[] = { -1.f, -1.f, 0.f,
1477 -1.f, 1.f, 0.f,
1478 1.f, 1.f, 0.f,
1479 1.f, 1.f, 0.f,
1480 1.f, -1.f, 0.f,
1481 -1.f, -1.f, 0.f };
265d4508 1482
fc73a202 1483 myRaytraceScreenQuad.Init (myGlContext, 3, 6, aVertices);
265d4508 1484
fc73a202 1485 myComputeInitStatus = OpenGl_RT_INIT; // initialized in normal way
1486
1487 return Standard_True;
1488}
265d4508 1489
fc73a202 1490// =======================================================================
1491// function : NullifyResource
1492// purpose :
1493// =======================================================================
1494inline void NullifyResource (const Handle(OpenGl_Context)& theContext,
1495 Handle(OpenGl_Resource)& theResource)
1496{
1497 if (!theResource.IsNull())
1498 {
1499 theResource->Release (theContext.operator->());
1500 theResource.Nullify();
1501 }
1502}
265d4508 1503
fc73a202 1504// =======================================================================
1505// function : ReleaseRaytraceResources
1506// purpose : Releases OpenGL/GLSL shader programs
1507// =======================================================================
1508void OpenGl_Workspace::ReleaseRaytraceResources()
1509{
a89742cf 1510 NullifyResource (myGlContext, myOpenGlFBO);
fc73a202 1511 NullifyResource (myGlContext, myRaytraceFBO1);
1512 NullifyResource (myGlContext, myRaytraceFBO2);
265d4508 1513
fc73a202 1514 NullifyResource (myGlContext, myRaytraceShader);
1515 NullifyResource (myGlContext, myPostFSAAShader);
265d4508 1516
fc73a202 1517 NullifyResource (myGlContext, myRaytraceProgram);
1518 NullifyResource (myGlContext, myPostFSAAProgram);
265d4508 1519
fc73a202 1520 NullifyResource (myGlContext, mySceneNodeInfoTexture);
1521 NullifyResource (myGlContext, mySceneMinPointTexture);
1522 NullifyResource (myGlContext, mySceneMaxPointTexture);
265d4508 1523
fc73a202 1524 NullifyResource (myGlContext, myObjectNodeInfoTexture);
1525 NullifyResource (myGlContext, myObjectMinPointTexture);
1526 NullifyResource (myGlContext, myObjectMaxPointTexture);
265d4508 1527
fc73a202 1528 NullifyResource (myGlContext, myGeometryVertexTexture);
1529 NullifyResource (myGlContext, myGeometryNormalTexture);
1530 NullifyResource (myGlContext, myGeometryTriangTexture);
bc8c79bb 1531 NullifyResource (myGlContext, mySceneTransformTexture);
265d4508 1532
fc73a202 1533 NullifyResource (myGlContext, myRaytraceLightSrcTexture);
1534 NullifyResource (myGlContext, myRaytraceMaterialTexture);
265d4508 1535
fc73a202 1536 if (myRaytraceScreenQuad.IsValid())
1537 myRaytraceScreenQuad.Release (myGlContext.operator->());
1538}
265d4508 1539
fc73a202 1540// =======================================================================
1541// function : UploadRaytraceData
1542// purpose : Uploads ray-trace data to the GPU
1543// =======================================================================
1544Standard_Boolean OpenGl_Workspace::UploadRaytraceData()
1545{
1546 if (!myGlContext->IsGlGreaterEqual (3, 1))
1547 {
265d4508 1548#ifdef RAY_TRACE_PRINT_INFO
fc73a202 1549 std::cout << "Error: OpenGL version is less than 3.1" << std::endl;
265d4508 1550#endif
fc73a202 1551 return Standard_False;
e276548b 1552 }
1553
265d4508 1554 /////////////////////////////////////////////////////////////////////////////
fc73a202 1555 // Create OpenGL texture buffers
265d4508 1556
fc73a202 1557 if (mySceneNodeInfoTexture.IsNull()) // create hight-level BVH buffers
e276548b 1558 {
fc73a202 1559 mySceneNodeInfoTexture = new OpenGl_TextureBufferArb;
1560 mySceneMinPointTexture = new OpenGl_TextureBufferArb;
1561 mySceneMaxPointTexture = new OpenGl_TextureBufferArb;
84c71f29 1562 mySceneTransformTexture = new OpenGl_TextureBufferArb;
265d4508 1563
fc73a202 1564 if (!mySceneNodeInfoTexture->Create (myGlContext)
84c71f29 1565 || !mySceneMinPointTexture->Create (myGlContext)
1566 || !mySceneMaxPointTexture->Create (myGlContext)
1567 || !mySceneTransformTexture->Create (myGlContext))
e276548b 1568 {
fc73a202 1569#ifdef RAY_TRACE_PRINT_INFO
1570 std::cout << "Error: Failed to create buffers for high-level scene BVH" << std::endl;
1571#endif
e276548b 1572 return Standard_False;
1573 }
1574 }
1575
fc73a202 1576 if (myObjectNodeInfoTexture.IsNull()) // create bottom-level BVH buffers
265d4508 1577 {
fc73a202 1578 myObjectNodeInfoTexture = new OpenGl_TextureBufferArb;
1579 myObjectMinPointTexture = new OpenGl_TextureBufferArb;
1580 myObjectMaxPointTexture = new OpenGl_TextureBufferArb;
e276548b 1581
fc73a202 1582 if (!myObjectNodeInfoTexture->Create (myGlContext)
1583 || !myObjectMinPointTexture->Create (myGlContext)
1584 || !myObjectMaxPointTexture->Create (myGlContext))
1585 {
e276548b 1586#ifdef RAY_TRACE_PRINT_INFO
fc73a202 1587 std::cout << "Error: Failed to create buffers for bottom-level scene BVH" << std::endl;
1588#endif
1589 return Standard_False;
1590 }
1591 }
5322131b 1592
fc73a202 1593 if (myGeometryVertexTexture.IsNull()) // create geometry buffers
265d4508 1594 {
fc73a202 1595 myGeometryVertexTexture = new OpenGl_TextureBufferArb;
1596 myGeometryNormalTexture = new OpenGl_TextureBufferArb;
1597 myGeometryTriangTexture = new OpenGl_TextureBufferArb;
e276548b 1598
fc73a202 1599 if (!myGeometryVertexTexture->Create (myGlContext)
1600 || !myGeometryNormalTexture->Create (myGlContext)
1601 || !myGeometryTriangTexture->Create (myGlContext))
1602 {
1603#ifdef RAY_TRACE_PRINT_INFO
1604 std::cout << "Error: Failed to create buffers for triangulation data" << std::endl;
1605#endif
1606 return Standard_False;
1607 }
265d4508 1608 }
5322131b 1609
fc73a202 1610 if (myRaytraceMaterialTexture.IsNull()) // create material buffer
1611 {
1612 myRaytraceMaterialTexture = new OpenGl_TextureBufferArb;
e276548b 1613
fc73a202 1614 if (!myRaytraceMaterialTexture->Create (myGlContext))
1615 {
1616#ifdef RAY_TRACE_PRINT_INFO
1617 std::cout << "Error: Failed to create buffers for material data" << std::endl;
e276548b 1618#endif
fc73a202 1619 return Standard_False;
1620 }
1621 }
e276548b 1622
fc73a202 1623 /////////////////////////////////////////////////////////////////////////////
bc8c79bb 1624 // Write top-level BVH buffers
e276548b 1625
fc73a202 1626 const NCollection_Handle<BVH_Tree<Standard_ShortReal, 4> >& aBVH = myRaytraceGeometry.BVH();
e276548b 1627
fc73a202 1628 bool aResult = true;
fc73a202 1629 if (!aBVH->NodeInfoBuffer().empty())
1630 {
5cff985a 1631 aResult &= mySceneNodeInfoTexture->Init (myGlContext, 4, GLsizei (aBVH->NodeInfoBuffer().size()),
1632 reinterpret_cast<const GLuint*> (&aBVH->NodeInfoBuffer().front()));
1633 aResult &= mySceneMinPointTexture->Init (myGlContext, 4, GLsizei (aBVH->MinPointBuffer().size()),
1634 reinterpret_cast<const GLfloat*> (&aBVH->MinPointBuffer().front()));
1635 aResult &= mySceneMaxPointTexture->Init (myGlContext, 4, GLsizei (aBVH->MaxPointBuffer().size()),
1636 reinterpret_cast<const GLfloat*> (&aBVH->MaxPointBuffer().front()));
fc73a202 1637 }
fc73a202 1638 if (!aResult)
1639 {
1640#ifdef RAY_TRACE_PRINT_INFO
1641 std::cout << "Error: Failed to upload buffers for high-level scene BVH" << std::endl;
1642#endif
e276548b 1643 return Standard_False;
1644 }
1645
84c71f29 1646 /////////////////////////////////////////////////////////////////////////////
1647 // Write transform buffer
1648
1649 BVH_Mat4f* aNodeTransforms = new BVH_Mat4f[myRaytraceGeometry.Size()];
1650 BVH_Mat4f anIdentity;
1651
1652 for (Standard_Integer anElemIndex = 0; anElemIndex < myRaytraceGeometry.Size(); ++anElemIndex)
1653 {
1654 OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
1655 myRaytraceGeometry.Objects().ChangeValue (anElemIndex).operator->());
1656
1657 const BVH_Transform<Standard_ShortReal, 4>* aTransform =
1658 dynamic_cast<const BVH_Transform<Standard_ShortReal, 4>* > (aTriangleSet->Properties().operator->());
1659
1660 Standard_ASSERT_RETURN (aTransform != NULL,
1661 "OpenGl_TriangleSet does not contain transform", Standard_False);
1662
1663 aNodeTransforms[anElemIndex] = aTransform->Inversed();
1664
1665 }
1666
1667 aResult &= mySceneTransformTexture->Init (myGlContext, 4,
1668 myRaytraceGeometry.Size() * 4, reinterpret_cast<const GLfloat*> (aNodeTransforms));
1669
1670 delete[] aNodeTransforms;
1671
1672 /////////////////////////////////////////////////////////////////////////////
bc8c79bb 1673 // Write geometry and bottom-level BVH buffers
84c71f29 1674
fc73a202 1675 Standard_Size aTotalVerticesNb = 0;
1676 Standard_Size aTotalElementsNb = 0;
1677 Standard_Size aTotalBVHNodesNb = 0;
265d4508 1678
fc73a202 1679 for (Standard_Integer anElemIndex = 0; anElemIndex < myRaytraceGeometry.Size(); ++anElemIndex)
1680 {
1681 OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
1682 myRaytraceGeometry.Objects().ChangeValue (anElemIndex).operator->());
265d4508 1683
fc73a202 1684 Standard_ASSERT_RETURN (aTriangleSet != NULL,
1685 "Error: Failed to get triangulation of OpenGL element", Standard_False);
1686
1687 aTotalVerticesNb += aTriangleSet->Vertices.size();
1688 aTotalElementsNb += aTriangleSet->Elements.size();
e276548b 1689
fc73a202 1690 Standard_ASSERT_RETURN (!aTriangleSet->BVH().IsNull(),
1691 "Error: Failed to get bottom-level BVH of OpenGL element", Standard_False);
265d4508 1692
fc73a202 1693 aTotalBVHNodesNb += aTriangleSet->BVH()->NodeInfoBuffer().size();
1694 }
e276548b 1695
fc73a202 1696 if (aTotalBVHNodesNb != 0)
e276548b 1697 {
5cff985a 1698 aResult &= myObjectNodeInfoTexture->Init (myGlContext, 4, GLsizei (aTotalBVHNodesNb), static_cast<const GLuint*> (NULL));
1699 aResult &= myObjectMinPointTexture->Init (myGlContext, 4, GLsizei (aTotalBVHNodesNb), static_cast<const GLfloat*> (NULL));
1700 aResult &= myObjectMaxPointTexture->Init (myGlContext, 4, GLsizei (aTotalBVHNodesNb), static_cast<const GLfloat*> (NULL));
fc73a202 1701 }
265d4508 1702
fc73a202 1703 if (!aResult)
1704 {
1705#ifdef RAY_TRACE_PRINT_INFO
1706 std::cout << "Error: Failed to upload buffers for bottom-level scene BVH" << std::endl;
1707#endif
1708 return Standard_False;
1709 }
e276548b 1710
fc73a202 1711 if (aTotalElementsNb != 0)
1712 {
5cff985a 1713 aResult &= myGeometryTriangTexture->Init (myGlContext, 4, GLsizei (aTotalElementsNb), static_cast<const GLuint*> (NULL));
fc73a202 1714 }
265d4508 1715
fc73a202 1716 if (aTotalVerticesNb != 0)
1717 {
5cff985a 1718 aResult &= myGeometryVertexTexture->Init (myGlContext, 4, GLsizei (aTotalVerticesNb), static_cast<const GLfloat*> (NULL));
1719 aResult &= myGeometryNormalTexture->Init (myGlContext, 4, GLsizei (aTotalVerticesNb), static_cast<const GLfloat*> (NULL));
fc73a202 1720 }
265d4508 1721
fc73a202 1722 if (!aResult)
1723 {
1724#ifdef RAY_TRACE_PRINT_INFO
1725 std::cout << "Error: Failed to upload buffers for scene geometry" << std::endl;
1726#endif
1727 return Standard_False;
1728 }
265d4508 1729
fc73a202 1730 for (Standard_Integer aNodeIdx = 0; aNodeIdx < aBVH->Length(); ++aNodeIdx)
1731 {
1732 if (!aBVH->IsOuter (aNodeIdx))
1733 continue;
265d4508 1734
fc73a202 1735 OpenGl_TriangleSet* aTriangleSet = myRaytraceGeometry.TriangleSet (aNodeIdx);
e276548b 1736
fc73a202 1737 Standard_ASSERT_RETURN (aTriangleSet != NULL,
1738 "Error: Failed to get triangulation of OpenGL element", Standard_False);
e276548b 1739
fc73a202 1740 const Standard_Integer aBVHOffset = myRaytraceGeometry.AccelerationOffset (aNodeIdx);
e276548b 1741
fc73a202 1742 Standard_ASSERT_RETURN (aBVHOffset != OpenGl_RaytraceGeometry::INVALID_OFFSET,
1743 "Error: Failed to get offset for bottom-level BVH", Standard_False);
e276548b 1744
fc73a202 1745 const size_t aBVHBuffserSize = aTriangleSet->BVH()->NodeInfoBuffer().size();
265d4508 1746
fc73a202 1747 if (aBVHBuffserSize != 0)
1748 {
5cff985a 1749 aResult &= myObjectNodeInfoTexture->SubData (myGlContext, aBVHOffset, GLsizei (aBVHBuffserSize),
1750 reinterpret_cast<const GLuint*> (&aTriangleSet->BVH()->NodeInfoBuffer().front()));
1751 aResult &= myObjectMinPointTexture->SubData (myGlContext, aBVHOffset, GLsizei (aBVHBuffserSize),
1752 reinterpret_cast<const GLfloat*> (&aTriangleSet->BVH()->MinPointBuffer().front()));
1753 aResult &= myObjectMaxPointTexture->SubData (myGlContext, aBVHOffset, GLsizei (aBVHBuffserSize),
1754 reinterpret_cast<const GLfloat*> (&aTriangleSet->BVH()->MaxPointBuffer().front()));
fc73a202 1755 if (!aResult)
e276548b 1756 {
fc73a202 1757#ifdef RAY_TRACE_PRINT_INFO
1758 std::cout << "Error: Failed to upload buffers for bottom-level scene BVHs" << std::endl;
1759#endif
e276548b 1760 return Standard_False;
1761 }
1762 }
1763
fc73a202 1764 const Standard_Integer aVerticesOffset = myRaytraceGeometry.VerticesOffset (aNodeIdx);
265d4508 1765
fc73a202 1766 Standard_ASSERT_RETURN (aVerticesOffset != OpenGl_RaytraceGeometry::INVALID_OFFSET,
1767 "Error: Failed to get offset for triangulation vertices of OpenGL element", Standard_False);
265d4508 1768
fc73a202 1769 if (!aTriangleSet->Vertices.empty())
1770 {
5cff985a 1771 aResult &= myGeometryNormalTexture->SubData (myGlContext, aVerticesOffset, GLsizei (aTriangleSet->Normals.size()),
1772 reinterpret_cast<const GLfloat*> (&aTriangleSet->Normals.front()));
1773 aResult &= myGeometryVertexTexture->SubData (myGlContext, aVerticesOffset, GLsizei (aTriangleSet->Vertices.size()),
1774 reinterpret_cast<const GLfloat*> (&aTriangleSet->Vertices.front()));
fc73a202 1775 }
e276548b 1776
fc73a202 1777 const Standard_Integer anElementsOffset = myRaytraceGeometry.ElementsOffset (aNodeIdx);
265d4508 1778
fc73a202 1779 Standard_ASSERT_RETURN (anElementsOffset != OpenGl_RaytraceGeometry::INVALID_OFFSET,
1780 "Error: Failed to get offset for triangulation elements of OpenGL element", Standard_False);
e276548b 1781
fc73a202 1782 if (!aTriangleSet->Elements.empty())
e276548b 1783 {
5cff985a 1784 aResult &= myGeometryTriangTexture->SubData (myGlContext, anElementsOffset, GLsizei (aTriangleSet->Elements.size()),
1785 reinterpret_cast<const GLuint*> (&aTriangleSet->Elements.front()));
e276548b 1786 }
265d4508 1787
fc73a202 1788 if (!aResult)
1789 {
1790#ifdef RAY_TRACE_PRINT_INFO
1791 std::cout << "Error: Failed to upload triangulation buffers for OpenGL element" << std::endl;
e276548b 1792#endif
fc73a202 1793 return Standard_False;
1794 }
e276548b 1795 }
e276548b 1796
fc73a202 1797 if (myRaytraceGeometry.Materials.size() != 0)
1798 {
1799 const GLfloat* aDataPtr = myRaytraceGeometry.Materials.front().Packed();
5cff985a 1800 aResult &= myRaytraceMaterialTexture->Init (myGlContext, 4, GLsizei (myRaytraceGeometry.Materials.size() * 7), aDataPtr);
fc73a202 1801 if (!aResult)
1802 {
1803#ifdef RAY_TRACE_PRINT_INFO
1804 std::cout << "Error: Failed to upload material buffer" << std::endl;
1805#endif
1806 return Standard_False;
1807 }
1808 }
e276548b 1809
fc73a202 1810 myIsRaytraceDataValid = myRaytraceGeometry.Objects().Size() != 0;
e276548b 1811
fc73a202 1812#ifdef RAY_TRACE_PRINT_INFO
e276548b 1813
fc73a202 1814 Standard_ShortReal aMemUsed = 0.f;
e276548b 1815
fc73a202 1816 for (Standard_Integer anElemIdx = 0; anElemIdx < myRaytraceGeometry.Size(); ++anElemIdx)
1817 {
1818 OpenGl_TriangleSet* aTriangleSet = dynamic_cast<OpenGl_TriangleSet*> (
1819 myRaytraceGeometry.Objects().ChangeValue (anElemIdx).operator->());
e276548b 1820
fc73a202 1821 aMemUsed += static_cast<Standard_ShortReal> (
1822 aTriangleSet->Vertices.size() * sizeof (BVH_Vec4f));
1823 aMemUsed += static_cast<Standard_ShortReal> (
1824 aTriangleSet->Normals.size() * sizeof (BVH_Vec4f));
1825 aMemUsed += static_cast<Standard_ShortReal> (
1826 aTriangleSet->Elements.size() * sizeof (BVH_Vec4i));
e276548b 1827
fc73a202 1828 aMemUsed += static_cast<Standard_ShortReal> (
1829 aTriangleSet->BVH()->NodeInfoBuffer().size() * sizeof (BVH_Vec4i));
1830 aMemUsed += static_cast<Standard_ShortReal> (
1831 aTriangleSet->BVH()->MinPointBuffer().size() * sizeof (BVH_Vec4f));
1832 aMemUsed += static_cast<Standard_ShortReal> (
1833 aTriangleSet->BVH()->MaxPointBuffer().size() * sizeof (BVH_Vec4f));
1834 }
e276548b 1835
fc73a202 1836 aMemUsed += static_cast<Standard_ShortReal> (
1837 myRaytraceGeometry.BVH()->NodeInfoBuffer().size() * sizeof (BVH_Vec4i));
1838 aMemUsed += static_cast<Standard_ShortReal> (
1839 myRaytraceGeometry.BVH()->MinPointBuffer().size() * sizeof (BVH_Vec4f));
1840 aMemUsed += static_cast<Standard_ShortReal> (
1841 myRaytraceGeometry.BVH()->MaxPointBuffer().size() * sizeof (BVH_Vec4f));
e276548b 1842
fc73a202 1843 std::cout << "GPU Memory Used (MB): ~" << aMemUsed / 1048576 << std::endl;
e276548b 1844
fc73a202 1845#endif
e276548b 1846
fc73a202 1847 return aResult;
1848}
e276548b 1849
fc73a202 1850// =======================================================================
1851// function : ResizeRaytraceBuffers
1852// purpose : Resizes OpenGL frame buffers
1853// =======================================================================
1854Standard_Boolean OpenGl_Workspace::ResizeRaytraceBuffers (const Standard_Integer theSizeX,
1855 const Standard_Integer theSizeY)
1856{
1857 if (myRaytraceFBO1->GetVPSizeX() != theSizeX
1858 || myRaytraceFBO1->GetVPSizeY() != theSizeY)
1859 {
1860 myRaytraceFBO1->Init (myGlContext, theSizeX, theSizeY);
1861 myRaytraceFBO2->Init (myGlContext, theSizeX, theSizeY);
1862 }
e276548b 1863
fc73a202 1864 return Standard_True;
e276548b 1865}
1866
1867// =======================================================================
fc73a202 1868// function : UpdateCamera
1869// purpose : Generates viewing rays for corners of screen quad
e276548b 1870// =======================================================================
fc73a202 1871void OpenGl_Workspace::UpdateCamera (const NCollection_Mat4<GLdouble>& theOrientation,
1872 const NCollection_Mat4<GLdouble>& theViewMapping,
1873 OpenGl_Vec3 theOrigins[4],
a89742cf 1874 OpenGl_Vec3 theDirects[4],
1875 NCollection_Mat4<GLdouble>& theInvModelProj)
e276548b 1876{
bc8c79bb 1877 // compute inverse model-view-projection matrix
a89742cf 1878 (theViewMapping * theOrientation).Inverted (theInvModelProj);
fc73a202 1879
68333c8f 1880 Standard_Integer aOriginIndex = 0;
1881 Standard_Integer aDirectIndex = 0;
e276548b 1882
fc73a202 1883 for (Standard_Integer aY = -1; aY <= 1; aY += 2)
e276548b 1884 {
fc73a202 1885 for (Standard_Integer aX = -1; aX <= 1; aX += 2)
e276548b 1886 {
fc73a202 1887 OpenGl_Vec4d aOrigin (GLdouble(aX),
1888 GLdouble(aY),
1889 -1.0,
1890 1.0);
1891
a89742cf 1892 aOrigin = theInvModelProj * aOrigin;
e276548b 1893
b5ac8292 1894 aOrigin.x() = aOrigin.x() / aOrigin.w();
1895 aOrigin.y() = aOrigin.y() / aOrigin.w();
1896 aOrigin.z() = aOrigin.z() / aOrigin.w();
e276548b 1897
fc73a202 1898 OpenGl_Vec4d aDirect (GLdouble(aX),
1899 GLdouble(aY),
1900 1.0,
1901 1.0);
1902
a89742cf 1903 aDirect = theInvModelProj * aDirect;
e276548b 1904
b5ac8292 1905 aDirect.x() = aDirect.x() / aDirect.w();
1906 aDirect.y() = aDirect.y() / aDirect.w();
1907 aDirect.z() = aDirect.z() / aDirect.w();
b5ac8292 1908
1909 aDirect = aDirect - aOrigin;
e276548b 1910
fc73a202 1911 GLdouble aInvLen = 1.0 / sqrt (aDirect.x() * aDirect.x() +
e276548b 1912 aDirect.y() * aDirect.y() +
1913 aDirect.z() * aDirect.z());
1914
fc73a202 1915 theOrigins[aOriginIndex++] = OpenGl_Vec3 (static_cast<GLfloat> (aOrigin.x()),
1916 static_cast<GLfloat> (aOrigin.y()),
1917 static_cast<GLfloat> (aOrigin.z()));
1918
1919 theDirects[aDirectIndex++] = OpenGl_Vec3 (static_cast<GLfloat> (aDirect.x() * aInvLen),
1920 static_cast<GLfloat> (aDirect.y() * aInvLen),
1921 static_cast<GLfloat> (aDirect.z() * aInvLen));
1922 }
1923 }
1924}
1925
1926// =======================================================================
1927// function : RunRaytraceShaders
1928// purpose : Runs ray-tracing shader programs
1929// =======================================================================
1930Standard_Boolean OpenGl_Workspace::RunRaytraceShaders (const Graphic3d_CView& theCView,
1931 const Standard_Integer theSizeX,
1932 const Standard_Integer theSizeY,
1933 const OpenGl_Vec3 theOrigins[4],
1934 const OpenGl_Vec3 theDirects[4],
a89742cf 1935 const OpenGl_Matrix& theInvModelProj,
fc73a202 1936 OpenGl_FrameBuffer* theFrameBuffer)
1937{
1938 mySceneMinPointTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneMinPointTexture);
1939 mySceneMaxPointTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneMaxPointTexture);
1940 mySceneNodeInfoTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneNodeInfoTexture);
1941 myObjectMinPointTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_ObjectMinPointTexture);
1942 myObjectMaxPointTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_ObjectMaxPointTexture);
1943 myObjectNodeInfoTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_ObjectNodeInfoTexture);
1944 myGeometryVertexTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryVertexTexture);
1945 myGeometryNormalTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryNormalTexture);
1946 myGeometryTriangTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryTriangTexture);
a89742cf 1947 mySceneTransformTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneTransformTexture);
fc73a202 1948 myRaytraceMaterialTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_RaytraceMaterialTexture);
1949 myRaytraceLightSrcTexture->BindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_RaytraceLightSrcTexture);
a89742cf 1950
1951 myOpenGlFBO->ColorTexture()->Bind (myGlContext, GL_TEXTURE0 + OpenGl_RT_OpenGlColorTexture);
1952 myOpenGlFBO->DepthStencilTexture()->Bind (myGlContext, GL_TEXTURE0 + OpenGl_RT_OpenGlDepthTexture);
fc73a202 1953
bc8c79bb 1954 if (theCView.RenderParams.IsAntialiasingEnabled) // render source image to FBO
fc73a202 1955 {
1956 myRaytraceFBO1->BindBuffer (myGlContext);
1957
1958 glDisable (GL_BLEND);
1959 }
1960
7d3e64ef 1961 myGlContext->BindProgram (myRaytraceProgram);
fc73a202 1962
1963 Standard_Integer aLightSourceBufferSize =
1964 static_cast<Standard_Integer> (myRaytraceGeometry.Sources.size());
1965
1966 myRaytraceProgram->SetUniform (myGlContext,
1967 myUniformLocations[0][OpenGl_RT_uOriginLB], theOrigins[0]);
1968 myRaytraceProgram->SetUniform (myGlContext,
1969 myUniformLocations[0][OpenGl_RT_uOriginRB], theOrigins[1]);
1970 myRaytraceProgram->SetUniform (myGlContext,
1971 myUniformLocations[0][OpenGl_RT_uOriginLT], theOrigins[2]);
1972 myRaytraceProgram->SetUniform (myGlContext,
1973 myUniformLocations[0][OpenGl_RT_uOriginRT], theOrigins[3]);
1974 myRaytraceProgram->SetUniform (myGlContext,
1975 myUniformLocations[0][OpenGl_RT_uDirectLB], theDirects[0]);
1976 myRaytraceProgram->SetUniform (myGlContext,
1977 myUniformLocations[0][OpenGl_RT_uDirectRB], theDirects[1]);
1978 myRaytraceProgram->SetUniform (myGlContext,
1979 myUniformLocations[0][OpenGl_RT_uDirectLT], theDirects[2]);
1980 myRaytraceProgram->SetUniform (myGlContext,
1981 myUniformLocations[0][OpenGl_RT_uDirectRT], theDirects[3]);
1982 myRaytraceProgram->SetUniform (myGlContext,
a89742cf 1983 myUniformLocations[0][OpenGl_RT_uInvModelProj], theInvModelProj);
1984 myRaytraceProgram->SetUniform (myGlContext,
fc73a202 1985 myUniformLocations[0][OpenGl_RT_uSceneRad], myRaytraceSceneRadius);
1986 myRaytraceProgram->SetUniform (myGlContext,
1987 myUniformLocations[0][OpenGl_RT_uSceneEps], myRaytraceSceneEpsilon);
1988 myRaytraceProgram->SetUniform (myGlContext,
1989 myUniformLocations[0][OpenGl_RT_uLightCount], aLightSourceBufferSize);
1990 myRaytraceProgram->SetUniform (myGlContext,
1991 myUniformLocations[0][OpenGl_RT_uLightAmbnt], myRaytraceGeometry.Ambient);
1992 myRaytraceProgram->SetUniform (myGlContext,
bc8c79bb 1993 myUniformLocations[0][OpenGl_RT_uShadEnabled], theCView.RenderParams.IsShadowEnabled ? 1 : 0);
fc73a202 1994 myRaytraceProgram->SetUniform (myGlContext,
bc8c79bb 1995 myUniformLocations[0][OpenGl_RT_uReflEnabled], theCView.RenderParams.IsReflectionEnabled ? 1 : 0);
fc73a202 1996
7d3e64ef 1997 myGlContext->core20fwd->glEnableVertexAttribArray (Graphic3d_TOA_POS);
fc73a202 1998 {
7d3e64ef 1999 myGlContext->core20fwd->glVertexAttribPointer (Graphic3d_TOA_POS, 3, GL_FLOAT, GL_FALSE, 0, NULL);
fc73a202 2000 myGlContext->core15fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
2001 }
7d3e64ef 2002 myGlContext->core20fwd->glDisableVertexAttribArray (Graphic3d_TOA_POS);
fc73a202 2003
bc8c79bb 2004 if (!theCView.RenderParams.IsAntialiasingEnabled)
fc73a202 2005 {
7d3e64ef 2006 myGlContext->BindProgram (NULL);
fc73a202 2007
a89742cf 2008 myOpenGlFBO->ColorTexture()->Unbind (myGlContext, GL_TEXTURE0 + OpenGl_RT_OpenGlColorTexture);
2009 myOpenGlFBO->DepthStencilTexture()->Unbind (myGlContext, GL_TEXTURE0 + OpenGl_RT_OpenGlDepthTexture);
2010 mySceneMinPointTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneMinPointTexture);
2011 mySceneMaxPointTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneMaxPointTexture);
2012 mySceneNodeInfoTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneNodeInfoTexture);
2013 myObjectMinPointTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_ObjectMinPointTexture);
2014 myObjectMaxPointTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_ObjectMaxPointTexture);
2015 myObjectNodeInfoTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_ObjectNodeInfoTexture);
2016 myGeometryVertexTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryVertexTexture);
2017 myGeometryNormalTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryNormalTexture);
2018 myGeometryTriangTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryTriangTexture);
2019 myRaytraceMaterialTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_RaytraceMaterialTexture);
2020 myRaytraceLightSrcTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_RaytraceLightSrcTexture);
2021 mySceneTransformTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneTransformTexture);
2022
2023 myGlContext->core15fwd->glActiveTexture (GL_TEXTURE0);
2024
fc73a202 2025 return Standard_True;
2026 }
2027
945c3529 2028 myRaytraceFBO1->ColorTexture()->Bind (myGlContext, GL_TEXTURE0 + OpenGl_RT_FSAAInputTexture);
fc73a202 2029
7d3e64ef 2030 myGlContext->BindProgram (myPostFSAAProgram);
fc73a202 2031
2032 myPostFSAAProgram->SetUniform (myGlContext,
2033 myUniformLocations[1][OpenGl_RT_uOriginLB], theOrigins[0]);
2034 myPostFSAAProgram->SetUniform (myGlContext,
2035 myUniformLocations[1][OpenGl_RT_uOriginRB], theOrigins[1]);
2036 myPostFSAAProgram->SetUniform (myGlContext,
2037 myUniformLocations[1][OpenGl_RT_uOriginLT], theOrigins[2]);
2038 myPostFSAAProgram->SetUniform (myGlContext,
2039 myUniformLocations[1][OpenGl_RT_uOriginRT], theOrigins[3]);
2040 myPostFSAAProgram->SetUniform (myGlContext,
2041 myUniformLocations[1][OpenGl_RT_uDirectLB], theDirects[0]);
2042 myPostFSAAProgram->SetUniform (myGlContext,
2043 myUniformLocations[1][OpenGl_RT_uDirectRB], theDirects[1]);
2044 myPostFSAAProgram->SetUniform (myGlContext,
2045 myUniformLocations[1][OpenGl_RT_uDirectLT], theDirects[2]);
2046 myPostFSAAProgram->SetUniform (myGlContext,
2047 myUniformLocations[1][OpenGl_RT_uDirectRT], theDirects[3]);
a89742cf 2048 myRaytraceProgram->SetUniform (myGlContext,
2049 myUniformLocations[1][OpenGl_RT_uInvModelProj], theInvModelProj);
fc73a202 2050 myPostFSAAProgram->SetUniform (myGlContext,
2051 myUniformLocations[1][OpenGl_RT_uSceneRad], myRaytraceSceneRadius);
2052 myPostFSAAProgram->SetUniform (myGlContext,
2053 myUniformLocations[1][OpenGl_RT_uSceneEps], myRaytraceSceneEpsilon);
2054 myPostFSAAProgram->SetUniform (myGlContext,
2055 myUniformLocations[1][OpenGl_RT_uLightCount], aLightSourceBufferSize);
2056 myPostFSAAProgram->SetUniform (myGlContext,
2057 myUniformLocations[1][OpenGl_RT_uLightAmbnt], myRaytraceGeometry.Ambient);
2058 myPostFSAAProgram->SetUniform (myGlContext,
bc8c79bb 2059 myUniformLocations[1][OpenGl_RT_uShadEnabled], theCView.RenderParams.IsShadowEnabled ? 1 : 0);
fc73a202 2060 myPostFSAAProgram->SetUniform (myGlContext,
bc8c79bb 2061 myUniformLocations[1][OpenGl_RT_uReflEnabled], theCView.RenderParams.IsReflectionEnabled ? 1 : 0);
fc73a202 2062
2063 const Standard_ShortReal aMaxOffset = 0.559017f;
2064 const Standard_ShortReal aMinOffset = 0.186339f;
2065
7d3e64ef 2066 myGlContext->core20fwd->glEnableVertexAttribArray (Graphic3d_TOA_POS);
2067 myGlContext->core20fwd->glVertexAttribPointer (Graphic3d_TOA_POS, 3, GL_FLOAT, GL_FALSE, 0, NULL);
fc73a202 2068
2069 // Perform multi-pass adaptive FSAA using ping-pong technique
84c71f29 2070 // rotated grid AA always uses 4 samples
fc73a202 2071 for (Standard_Integer anIt = 0; anIt < 4; ++anIt)
2072 {
2073 GLfloat aOffsetX = 1.f / theSizeX;
2074 GLfloat aOffsetY = 1.f / theSizeY;
2075
2076 if (anIt < 2)
2077 {
2078 aOffsetX *= anIt < 1 ? aMinOffset : -aMaxOffset;
2079 aOffsetY *= anIt < 1 ? aMaxOffset : aMinOffset;
2080 }
2081 else
2082 {
2083 aOffsetX *= anIt > 2 ? aMaxOffset : -aMinOffset;
2084 aOffsetY *= anIt > 2 ? -aMinOffset : -aMaxOffset;
2085 }
2086
2087 myPostFSAAProgram->SetUniform (myGlContext,
2088 myUniformLocations[1][OpenGl_RT_uSamples], anIt + 2);
2089 myPostFSAAProgram->SetUniform (myGlContext,
2090 myUniformLocations[1][OpenGl_RT_uOffsetX], aOffsetX);
2091 myPostFSAAProgram->SetUniform (myGlContext,
2092 myUniformLocations[1][OpenGl_RT_uOffsetY], aOffsetY);
2093
2094 Handle(OpenGl_FrameBuffer)& aFramebuffer = anIt % 2 ? myRaytraceFBO1 : myRaytraceFBO2;
2095
2096 if (anIt == 3) // disable FBO on last iteration
2097 {
2098 glEnable (GL_BLEND);
2099
2100 if (theFrameBuffer != NULL)
2101 theFrameBuffer->BindBuffer (myGlContext);
2102 }
2103 else
2104 {
2105 aFramebuffer->BindBuffer (myGlContext);
2106 }
2107
2108 myGlContext->core15fwd->glDrawArrays (GL_TRIANGLES, 0, 6);
e276548b 2109
fc73a202 2110 if (anIt != 3) // set input for the next pass
2111 {
945c3529 2112 aFramebuffer->ColorTexture()->Bind (myGlContext, GL_TEXTURE0 + OpenGl_RT_FSAAInputTexture);
fc73a202 2113 aFramebuffer->UnbindBuffer (myGlContext);
e276548b 2114 }
2115 }
fc73a202 2116
7d3e64ef 2117 myGlContext->core20fwd->glDisableVertexAttribArray (Graphic3d_TOA_POS);
fc73a202 2118
7d3e64ef 2119 myGlContext->BindProgram (NULL);
a89742cf 2120 myRaytraceFBO1->ColorTexture()->Unbind (myGlContext, GL_TEXTURE0 + OpenGl_RT_FSAAInputTexture);
2121 myOpenGlFBO->ColorTexture()->Unbind (myGlContext, GL_TEXTURE0 + OpenGl_RT_OpenGlColorTexture);
2122 myOpenGlFBO->DepthStencilTexture()->Unbind (myGlContext, GL_TEXTURE0 + OpenGl_RT_OpenGlDepthTexture);
2123 mySceneMinPointTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneMinPointTexture);
2124 mySceneMaxPointTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneMaxPointTexture);
2125 mySceneNodeInfoTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneNodeInfoTexture);
2126 myObjectMinPointTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_ObjectMinPointTexture);
2127 myObjectMaxPointTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_ObjectMaxPointTexture);
2128 myObjectNodeInfoTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_ObjectNodeInfoTexture);
2129 myGeometryVertexTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryVertexTexture);
2130 myGeometryNormalTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryNormalTexture);
2131 myGeometryTriangTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_GeometryTriangTexture);
2132 myRaytraceMaterialTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_RaytraceMaterialTexture);
2133 myRaytraceLightSrcTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_RaytraceLightSrcTexture);
2134 mySceneTransformTexture->UnbindTexture (myGlContext, GL_TEXTURE0 + OpenGl_RT_SceneTransformTexture);
2135
2136 myGlContext->core15fwd->glActiveTexture (GL_TEXTURE0);
fc73a202 2137
2138 return Standard_True;
e276548b 2139}
2140
2141// =======================================================================
2142// function : Raytrace
fc73a202 2143// purpose : Redraws the window using OpenGL/GLSL ray-tracing
e276548b 2144// =======================================================================
2145Standard_Boolean OpenGl_Workspace::Raytrace (const Graphic3d_CView& theCView,
68333c8f 2146 const Standard_Integer theSizeX,
2147 const Standard_Integer theSizeY,
fc73a202 2148 const Standard_Boolean theToSwap,
a89742cf 2149 const Aspect_CLayer2d& theCOverLayer,
2150 const Aspect_CLayer2d& theCUnderLayer,
fc73a202 2151 OpenGl_FrameBuffer* theFrameBuffer)
e276548b 2152{
bc8c79bb 2153 if (!InitRaytraceResources (theCView))
e276548b 2154 return Standard_False;
2155
fc73a202 2156 if (!ResizeRaytraceBuffers (theSizeX, theSizeY))
e276548b 2157 return Standard_False;
2158
fc73a202 2159 if (!UpdateRaytraceEnvironmentMap())
e276548b 2160 return Standard_False;
2161
2162 // Get model-view and projection matrices
2163 TColStd_Array2OfReal theOrientation (0, 3, 0, 3);
2164 TColStd_Array2OfReal theViewMapping (0, 3, 0, 3);
2165
b5ac8292 2166 myView->GetMatrices (theOrientation, theViewMapping);
e276548b 2167
fc73a202 2168 NCollection_Mat4<GLdouble> aOrientationMatrix;
2169 NCollection_Mat4<GLdouble> aViewMappingMatrix;
e276548b 2170
68333c8f 2171 for (Standard_Integer j = 0; j < 4; ++j)
fc73a202 2172 {
68333c8f 2173 for (Standard_Integer i = 0; i < 4; ++i)
e276548b 2174 {
2175 aOrientationMatrix [4 * j + i] = theOrientation (i, j);
2176 aViewMappingMatrix [4 * j + i] = theViewMapping (i, j);
2177 }
fc73a202 2178 }
2179
2180 NCollection_Mat4<GLdouble> aInvOrientationMatrix;
2181 aOrientationMatrix.Inverted (aInvOrientationMatrix);
e276548b 2182
fc73a202 2183 if (!UpdateRaytraceLightSources (aInvOrientationMatrix))
e276548b 2184 return Standard_False;
2185
fc73a202 2186 OpenGl_Vec3 aOrigins[4];
2187 OpenGl_Vec3 aDirects[4];
a89742cf 2188 NCollection_Mat4<GLdouble> anInvModelProj;
e276548b 2189
fc73a202 2190 UpdateCamera (aOrientationMatrix,
2191 aViewMappingMatrix,
2192 aOrigins,
a89742cf 2193 aDirects,
2194 anInvModelProj);
2195
2196 OpenGl_Matrix anInvModelProjMatrix;
2197 for (Standard_Integer j = 0; j < 4; ++j)
2198 {
2199 for (Standard_Integer i = 0; i < 4; ++i)
2200 {
2201 anInvModelProjMatrix.mat[j][i] = static_cast<GLfloat>(anInvModelProj.GetValue(i,j));
2202 }
2203 }
e276548b 2204
84c71f29 2205 Standard_Boolean wasBlendingEnabled = glIsEnabled (GL_BLEND);
2206 Standard_Boolean wasDepthTestEnabled = glIsEnabled (GL_DEPTH_TEST);
e276548b 2207
2208 glDisable (GL_DEPTH_TEST);
2209
a89742cf 2210 if (theFrameBuffer != NULL)
2211 {
2212 theFrameBuffer->BindBuffer (myGlContext);
2213 }
2214
e276548b 2215 if (NamedStatus & OPENGL_NS_WHITEBACK)
2216 {
2217 glClearColor (1.0f, 1.0f, 1.0f, 1.0f);
2218 }
2219 else
2220 {
2221 glClearColor (myBgColor.rgb[0],
2222 myBgColor.rgb[1],
2223 myBgColor.rgb[2],
2224 1.0f);
2225 }
2226
2227 glClear (GL_COLOR_BUFFER_BIT);
2228
fc73a202 2229 myView->DrawBackground (*this);
e276548b 2230
a89742cf 2231 myView->RedrawLayer2d (myPrintContext, theCView, theCUnderLayer);
2232
fc73a202 2233 // Generate ray-traced image
e276548b 2234 glMatrixMode (GL_PROJECTION);
a89742cf 2235 glPushMatrix();
e276548b 2236 glLoadIdentity();
2237
2238 glMatrixMode (GL_MODELVIEW);
a89742cf 2239 glPushMatrix();
e276548b 2240 glLoadIdentity();
2241
fc73a202 2242 glEnable (GL_BLEND);
2243 glBlendFunc (GL_ONE, GL_SRC_ALPHA);
e276548b 2244
2245 if (myIsRaytraceDataValid)
2246 {
fc73a202 2247 myRaytraceScreenQuad.Bind (myGlContext);
2248
2249 RunRaytraceShaders (theCView,
2250 theSizeX,
2251 theSizeY,
2252 aOrigins,
2253 aDirects,
a89742cf 2254 anInvModelProjMatrix,
fc73a202 2255 theFrameBuffer);
2256
2257 myRaytraceScreenQuad.Unbind (myGlContext);
e276548b 2258 }
2259
84c71f29 2260 if (!wasBlendingEnabled)
2261 glDisable (GL_BLEND);
fc73a202 2262
84c71f29 2263 if (wasDepthTestEnabled)
2264 glEnable (GL_DEPTH_TEST);
e276548b 2265
a89742cf 2266 glMatrixMode (GL_PROJECTION);
2267 glPopMatrix();
2268 glMatrixMode (GL_MODELVIEW);
2269 glPopMatrix();
2270
2271 // Redraw trihedron
2272 myView->RedrawTrihedron (this);
2273
2274 // Redraw overlay
2275 const int aMode = 0;
2276 DisplayCallback (theCView, (aMode | OCC_PRE_OVERLAY));
2277 myView->RedrawLayer2d (myPrintContext, theCView, theCOverLayer);
2278 DisplayCallback (theCView, aMode);
2279
e276548b 2280 // Swap the buffers
2281 if (theToSwap)
2282 {
2283 GetGlContext()->SwapBuffers();
2284 myBackBufferRestored = Standard_False;
2285 }
2286 else
fc73a202 2287 {
e276548b 2288 glFlush();
fc73a202 2289 }
e276548b 2290
2291 return Standard_True;
2292}
a89742cf 2293
2294IMPLEMENT_STANDARD_HANDLE(OpenGl_RaytraceFilter, OpenGl_RenderFilter)
2295IMPLEMENT_STANDARD_RTTIEXT(OpenGl_RaytraceFilter, OpenGl_RenderFilter)
2296
2297// =======================================================================
2298// function : CanRender
2299// purpose :
2300// =======================================================================
2301Standard_Boolean OpenGl_RaytraceFilter::CanRender (const OpenGl_Element* theElement)
2302{
2303 Standard_Boolean aPrevFilterResult = Standard_True;
2304 if (!myPrevRenderFilter.IsNull())
2305 {
2306 aPrevFilterResult = myPrevRenderFilter->CanRender(theElement);
2307 }
2308 return aPrevFilterResult &&
2309 !OpenGl_Raytrace::IsRaytracedElement (theElement);
2310}