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