1 // Created on: 2013-08-27
2 // Created by: Denis BOGOLEPOV
3 // Copyright (c) 2013 OPEN CASCADE SAS
5 // The content of this file is subject to the Open CASCADE Technology Public
6 // License Version 6.5 (the "License"). You may not use the content of this file
7 // except in compliance with the License. Please obtain a copy of the License
8 // at http://www.opencascade.org and read it completely before using this file.
10 // The Initial Developer of the Original Code is Open CASCADE S.A.S., having its
11 // main offices at: 1, place des Freres Montgolfier, 78280 Guyancourt, France.
13 // The Original Code and all software distributed under the License is
14 // distributed on an "AS IS" basis, without warranty of any kind, and the
15 // Initial Developer hereby disclaims all such warranties, including without
16 // limitation, any warranties of merchantability, fitness for a particular
17 // purpose or non-infringement. Please see the License for the specific terms
18 // and conditions governing the rights and limitations under the License.
31 #pragma comment (lib, "DelayImp.lib")
32 #pragma comment (lib, "OpenCL.lib")
34 #elif defined(__APPLE__) && !defined(MACOSX_USE_GLX)
35 #include <OpenGL/CGLCurrent.h>
40 #include <OpenGl_Context.hxx>
41 #include <OpenGl_Texture.hxx>
42 #include <OpenGl_View.hxx>
43 #include <OpenGl_Workspace.hxx>
45 using namespace OpenGl_Raytrace;
47 //! Use this macro to output ray-tracing debug info
48 // #define RAY_TRACE_PRINT_INFO
50 #ifdef RAY_TRACE_PRINT_INFO
51 #include <OSD_Timer.hxx>
54 //! OpenCL source of ray-tracing kernels.
55 extern const char THE_RAY_TRACE_OPENCL_SOURCE[];
57 // =======================================================================
58 // function : MatVecMult
59 // purpose : Multiples 4x4 matrix by 4D vector
60 // =======================================================================
61 template< typename T >
62 OpenGl_RTVec4f MatVecMult (const T m[16], const OpenGl_RTVec4f& v)
64 return OpenGl_RTVec4f (
65 static_cast<float> (m[ 0] * v.x() + m[ 4] * v.y() +
66 m[ 8] * v.z() + m[12] * v.w()),
67 static_cast<float> (m[ 1] * v.x() + m[ 5] * v.y() +
68 m[ 9] * v.z() + m[13] * v.w()),
69 static_cast<float> (m[ 2] * v.x() + m[ 6] * v.y() +
70 m[10] * v.z() + m[14] * v.w()),
71 static_cast<float> (m[ 3] * v.x() + m[ 7] * v.y() +
72 m[11] * v.z() + m[15] * v.w()));
75 // =======================================================================
76 // function : UpdateRaytraceEnvironmentMap
77 // purpose : Updates environment map for ray-tracing
78 // =======================================================================
79 Standard_Boolean OpenGl_Workspace::UpdateRaytraceEnvironmentMap()
82 return Standard_False;
84 if (myViewModificationStatus == myView->ModificationState())
87 cl_int anError = CL_SUCCESS;
89 if (myRaytraceEnvironment != NULL)
90 clReleaseMemObject (myRaytraceEnvironment);
95 if (!myView->TextureEnv().IsNull() && myView->SurfaceDetail() != Visual3d_TOD_NONE)
97 aSizeX = (myView->TextureEnv()->SizeX() <= 0) ? 1 : myView->TextureEnv()->SizeX();
98 aSizeY = (myView->TextureEnv()->SizeY() <= 0) ? 1 : myView->TextureEnv()->SizeY();
101 cl_image_format aImageFormat;
103 aImageFormat.image_channel_order = CL_RGBA;
104 aImageFormat.image_channel_data_type = CL_FLOAT;
106 myRaytraceEnvironment = clCreateImage2D (myComputeContext, CL_MEM_READ_ONLY,
107 &aImageFormat, aSizeX, aSizeY, 0,
110 cl_float* aPixelData = new cl_float[aSizeX * aSizeY * 4];
112 // Note: texture format is not compatible with OpenCL image
113 // (it's not possible to create image directly from texture)
115 if (!myView->TextureEnv().IsNull() && myView->SurfaceDetail() != Visual3d_TOD_NONE)
117 myView->TextureEnv()->Bind (GetGlContext());
119 glGetTexImage (GL_TEXTURE_2D,
125 myView->TextureEnv()->Unbind (GetGlContext());
129 for (int aPixel = 0; aPixel < aSizeX * aSizeY * 4; ++aPixel)
130 aPixelData[aPixel] = 0.f;
133 size_t anImageOffset[] = { 0,
137 size_t anImageRegion[] = { aSizeX,
141 anError |= clEnqueueWriteImage (myRaytraceQueue, myRaytraceEnvironment, CL_TRUE,
142 anImageOffset, anImageRegion, 0, 0, aPixelData,
144 #ifdef RAY_TRACE_PRINT_INFO
145 if (anError != CL_SUCCESS)
146 std::cout << "Error! Failed to write environment map image!" << std::endl;
151 myViewModificationStatus = myView->ModificationState();
153 return (anError == CL_SUCCESS);
156 // =======================================================================
157 // function : UpdateRaytraceGeometry
158 // purpose : Updates 3D scene geometry for ray tracing
159 // =======================================================================
160 Standard_Boolean OpenGl_Workspace::UpdateRaytraceGeometry (Standard_Boolean theCheck)
163 return Standard_False;
165 // Note: In 'check' mode the scene geometry is analyzed for modifications
166 // This is light-weight procedure performed for each frame
170 myRaytraceSceneData.Clear();
172 myIsRaytraceDataValid = Standard_False;
176 if (myLayersModificationStatus != myView->LayerList().ModificationState())
178 return UpdateRaytraceGeometry (Standard_False);
182 float* aTransform (NULL);
184 // The set of processed structures (reflected to ray-tracing)
185 // This set is used to remove out-of-date records from the
186 // hash map of structures
187 std::set<const OpenGl_Structure*> anElements;
189 const OpenGl_LayerList& aList = myView->LayerList();
191 for (OpenGl_SequenceOfLayers::Iterator anLayerIt (aList.Layers()); anLayerIt.More(); anLayerIt.Next())
193 const OpenGl_PriorityList& aPriorityList = anLayerIt.Value();
195 if (aPriorityList.NbStructures() == 0)
198 const OpenGl_ArrayOfStructure& aStructArray = aPriorityList.ArrayOfStructures();
200 for (int anIndex = 0; anIndex < aStructArray.Length(); ++anIndex)
202 OpenGl_SequenceOfStructure::Iterator aStructIt;
204 for (aStructIt.Init (aStructArray (anIndex)); aStructIt.More(); aStructIt.Next())
206 const OpenGl_Structure* aStructure = aStructIt.Value();
210 if (CheckRaytraceStructure (aStructure))
212 return UpdateRaytraceGeometry (Standard_False);
217 if (!aStructure->IsRaytracable())
220 if (aStructure->Transformation()->mat != NULL)
222 if (aTransform == NULL)
223 aTransform = new float[16];
225 for (int i = 0; i < 4; ++i)
226 for (int j = 0; j < 4; ++j)
228 aTransform[j * 4 + i] = aStructure->Transformation()->mat[i][j];
232 AddRaytraceStructure (aStructure, aTransform, anElements);
240 // Actualize the hash map of structures -- remove out-of-date records
241 std::map<const OpenGl_Structure*, Standard_Size>::iterator anIter = myStructureStates.begin();
243 while (anIter != myStructureStates.end())
245 if (anElements.find (anIter->first) == anElements.end())
247 myStructureStates.erase (anIter++);
255 // Actualize OpenGL layer list state
256 myLayersModificationStatus = myView->LayerList().ModificationState();
259 #ifdef RAY_TRACE_PRINT_INFO
264 myBVHBuilder.Build (myRaytraceSceneData);
266 #ifdef RAY_TRACE_PRINT_INFO
267 std::cout << " Build time: " << aTimer.ElapsedTime() << " for "
268 << myRaytraceSceneData.Triangles.size() / 1000 << "K triangles" << std::endl;
271 const float aScaleFactor = 1.5f;
273 myRaytraceSceneRadius = aScaleFactor *
274 Max ( Max (fabsf (myRaytraceSceneData.AABB.CornerMin().x()),
275 Max (fabsf (myRaytraceSceneData.AABB.CornerMin().y()),
276 fabsf (myRaytraceSceneData.AABB.CornerMin().z()))),
277 Max (fabsf (myRaytraceSceneData.AABB.CornerMax().x()),
278 Max (fabsf (myRaytraceSceneData.AABB.CornerMax().y()),
279 fabsf (myRaytraceSceneData.AABB.CornerMax().z()))) );
281 myRaytraceSceneEpsilon = Max (1e-4f, myRaytraceSceneRadius * 1e-4f);
283 return WriteRaytraceSceneToDevice();
286 delete [] aTransform;
288 return Standard_True;
291 // =======================================================================
292 // function : CheckRaytraceStructure
293 // purpose : Adds OpenGL structure to ray-traced scene geometry
294 // =======================================================================
295 Standard_Boolean OpenGl_Workspace::CheckRaytraceStructure (const OpenGl_Structure* theStructure)
297 if (!theStructure->IsRaytracable())
299 // Checks to see if all ray-tracable elements were
300 // removed from the structure
301 if (theStructure->ModificationState() > 0)
303 theStructure->ResetModificationState();
304 return Standard_True;
307 return Standard_False;
310 std::map<const OpenGl_Structure*, Standard_Size>::iterator aStructState = myStructureStates.find (theStructure);
312 if (aStructState != myStructureStates.end())
313 return aStructState->second != theStructure->ModificationState();
315 return Standard_True;
318 // =======================================================================
319 // function : CreateMaterial
320 // purpose : Creates ray-tracing material properties
321 // =======================================================================
322 void CreateMaterial (const OPENGL_SURF_PROP& theProp, OpenGl_RaytraceMaterial& theMaterial)
324 theMaterial.Ambient = OpenGl_RTVec4f (theProp.ambcol.rgb[0] * theProp.amb,
325 theProp.ambcol.rgb[1] * theProp.amb,
326 theProp.ambcol.rgb[2] * theProp.amb,
329 theMaterial.Diffuse = OpenGl_RTVec4f (theProp.difcol.rgb[0] * theProp.diff,
330 theProp.difcol.rgb[1] * theProp.diff,
331 theProp.difcol.rgb[2] * theProp.diff,
334 theMaterial.Specular = OpenGl_RTVec4f (theProp.speccol.rgb[0] * theProp.spec,
335 theProp.speccol.rgb[1] * theProp.spec,
336 theProp.speccol.rgb[2] * theProp.spec,
339 theMaterial.Emission = OpenGl_RTVec4f (theProp.emscol.rgb[0] * theProp.emsv,
340 theProp.emscol.rgb[1] * theProp.emsv,
341 theProp.emscol.rgb[2] * theProp.emsv,
344 // Note: Here we use sub-linear transparency function
345 // to produce realistic-looking transparency effect
346 theMaterial.Transparency = OpenGl_RTVec4f (powf (theProp.trans, 0.75f),
351 const float aMaxRefl = Max (theMaterial.Diffuse.x() + theMaterial.Specular.x(),
352 Max (theMaterial.Diffuse.y() + theMaterial.Specular.y(),
353 theMaterial.Diffuse.z() + theMaterial.Specular.z()));
355 const float aReflectionScale = 0.75f / aMaxRefl;
357 theMaterial.Reflection = OpenGl_RTVec4f (theProp.speccol.rgb[0] * theProp.spec,
358 theProp.speccol.rgb[1] * theProp.spec,
359 theProp.speccol.rgb[2] * theProp.spec,
360 0.f) * aReflectionScale;
363 // =======================================================================
364 // function : AddRaytraceStructure
365 // purpose : Adds OpenGL structure to ray-traced scene geometry
366 // =======================================================================
367 Standard_Boolean OpenGl_Workspace::AddRaytraceStructure (const OpenGl_Structure* theStructure,
368 const float* theTransform,
369 std::set<const OpenGl_Structure*>& theElements)
371 #ifdef RAY_TRACE_PRINT_INFO
372 std::cout << "Add Structure" << std::endl;
375 theElements.insert (theStructure);
377 if (!theStructure->IsVisible())
379 myStructureStates[theStructure] = theStructure->ModificationState();
380 return Standard_True;
383 // Get structure material
384 int aStructMatID = -1;
386 if (theStructure->AspectFace() != NULL)
388 aStructMatID = static_cast<int> (myRaytraceSceneData.Materials.size());
390 OpenGl_RaytraceMaterial aStructMaterial;
391 CreateMaterial (theStructure->AspectFace()->IntFront(), aStructMaterial);
393 myRaytraceSceneData.Materials.push_back (aStructMaterial);
396 OpenGl_ListOfGroup::Iterator anItg (theStructure->Groups());
400 // Get group material
401 int aGroupMatID = -1;
403 if (anItg.Value()->AspectFace() != NULL)
405 aGroupMatID = static_cast<int> (myRaytraceSceneData.Materials.size());
407 OpenGl_RaytraceMaterial aGroupMaterial;
408 CreateMaterial (anItg.Value()->AspectFace()->IntFront(), aGroupMaterial);
410 myRaytraceSceneData.Materials.push_back (aGroupMaterial);
413 int aMatID = aGroupMatID < 0 ? aStructMatID : aGroupMatID;
415 if (aStructMatID < 0 && aGroupMatID < 0)
417 aMatID = static_cast<int> (myRaytraceSceneData.Materials.size());
419 myRaytraceSceneData.Materials.push_back (OpenGl_RaytraceMaterial());
422 // Add OpenGL elements from group (only arrays of primitives)
423 for (const OpenGl_ElementNode* aNode = anItg.Value()->FirstNode(); aNode != NULL; aNode = aNode->next)
425 if (TelNil == aNode->type)
427 OpenGl_AspectFace* anAspect = dynamic_cast<OpenGl_AspectFace*> (aNode->elem);
429 if (anAspect != NULL)
431 aMatID = static_cast<int> (myRaytraceSceneData.Materials.size());
433 OpenGl_RaytraceMaterial aMaterial;
434 CreateMaterial (anAspect->IntFront(), aMaterial);
436 myRaytraceSceneData.Materials.push_back (aMaterial);
439 else if (TelParray == aNode->type)
441 OpenGl_PrimitiveArray* aPrimArray = dynamic_cast<OpenGl_PrimitiveArray*> (aNode->elem);
443 if (aPrimArray != NULL)
445 AddRaytracePrimitiveArray (aPrimArray->PArray(), aMatID, theTransform);
453 float* aTransform (NULL);
455 // Process all connected OpenGL structures
456 OpenGl_ListOfStructure::Iterator anIts (theStructure->ConnectedStructures());
460 if (anIts.Value()->Transformation()->mat != NULL)
462 float* aTransform = new float[16];
464 for (int i = 0; i < 4; ++i)
465 for (int j = 0; j < 4; ++j)
467 aTransform[j * 4 + i] =
468 anIts.Value()->Transformation()->mat[i][j];
472 if (anIts.Value()->IsRaytracable())
473 AddRaytraceStructure (anIts.Value(), aTransform != NULL ? aTransform : theTransform, theElements);
480 myStructureStates[theStructure] = theStructure->ModificationState();
482 return Standard_True;
485 // =======================================================================
486 // function : AddRaytracePrimitiveArray
487 // purpose : Adds OpenGL primitive array to ray-traced scene geometry
488 // =======================================================================
489 Standard_Boolean OpenGl_Workspace::AddRaytracePrimitiveArray (const CALL_DEF_PARRAY* theArray,
491 const float* theTransform)
493 if (theArray->type != TelPolygonsArrayType &&
494 theArray->type != TelTrianglesArrayType &&
495 theArray->type != TelQuadranglesArrayType &&
496 theArray->type != TelTriangleFansArrayType &&
497 theArray->type != TelTriangleStripsArrayType &&
498 theArray->type != TelQuadrangleStripsArrayType)
500 return Standard_True;
503 if (theArray->vertices == NULL)
504 return Standard_False;
506 #ifdef RAY_TRACE_PRINT_INFO
507 switch (theArray->type)
509 case TelPolygonsArrayType:
510 std::cout << "\tTelPolygonsArrayType" << std::endl; break;
511 case TelTrianglesArrayType:
512 std::cout << "\tTelTrianglesArrayType" << std::endl; break;
513 case TelQuadranglesArrayType:
514 std::cout << "\tTelQuadranglesArrayType" << std::endl; break;
515 case TelTriangleFansArrayType:
516 std::cout << "\tTelTriangleFansArrayType" << std::endl; break;
517 case TelTriangleStripsArrayType:
518 std::cout << "\tTelTriangleStripsArrayType" << std::endl; break;
519 case TelQuadrangleStripsArrayType:
520 std::cout << "\tTelQuadrangleStripsArrayType" << std::endl; break;
524 // Simple optimization to eliminate possible memory allocations
525 // during processing of the primitive array vertices
526 myRaytraceSceneData.Vertices.reserve (
527 myRaytraceSceneData.Vertices.size() + theArray->num_vertexs);
529 const int aFirstVert = static_cast<int> (myRaytraceSceneData.Vertices.size());
531 for (int aVert = 0; aVert < theArray->num_vertexs; ++aVert)
533 OpenGl_RTVec4f aVertex (theArray->vertices[aVert].xyz[0],
534 theArray->vertices[aVert].xyz[1],
535 theArray->vertices[aVert].xyz[2],
539 aVertex = MatVecMult (theTransform, aVertex);
541 myRaytraceSceneData.Vertices.push_back (aVertex);
543 myRaytraceSceneData.AABB.Add (aVertex);
546 myRaytraceSceneData.Normals.reserve (
547 myRaytraceSceneData.Normals.size() + theArray->num_vertexs);
549 for (int aNorm = 0; aNorm < theArray->num_vertexs; ++aNorm)
551 OpenGl_RTVec4f aNormal;
553 // Note: In case of absence of normals, the visualizer
554 // will use generated geometric normals
556 if (theArray->vnormals != NULL)
558 aNormal = OpenGl_RTVec4f (theArray->vnormals[aNorm].xyz[0],
559 theArray->vnormals[aNorm].xyz[1],
560 theArray->vnormals[aNorm].xyz[2],
564 aNormal = MatVecMult (theTransform, aNormal);
567 myRaytraceSceneData.Normals.push_back (aNormal);
570 if (theArray->num_bounds > 0)
572 #ifdef RAY_TRACE_PRINT_INFO
573 std::cout << "\tNumber of bounds = " << theArray->num_bounds << std::endl;
578 for (int aBound = 0; aBound < theArray->num_bounds; ++aBound)
580 const int aVertNum = theArray->bounds[aBound];
582 #ifdef RAY_TRACE_PRINT_INFO
583 std::cout << "\tAdd indices from bound " << aBound << ": " <<
584 aVertOffset << ", " << aVertNum << std::endl;
587 if (!AddRaytraceVertexIndices (theArray, aFirstVert, aVertOffset, aVertNum, theMatID))
589 return Standard_False;
592 aVertOffset += aVertNum;
597 const int aVertNum = theArray->num_edges > 0 ? theArray->num_edges : theArray->num_vertexs;
599 #ifdef RAY_TRACE_PRINT_INFO
600 std::cout << "\tAdd indices: " << aVertNum << std::endl;
603 return AddRaytraceVertexIndices (theArray, aFirstVert, 0, aVertNum, theMatID);
606 return Standard_True;
609 // =======================================================================
610 // function : AddRaytraceVertexIndices
611 // purpose : Adds vertex indices to ray-traced scene geometry
612 // =======================================================================
613 Standard_Boolean OpenGl_Workspace::AddRaytraceVertexIndices (const CALL_DEF_PARRAY* theArray,
619 myRaytraceSceneData.Triangles.reserve (myRaytraceSceneData.Triangles.size() + theVertNum);
621 switch (theArray->type)
623 case TelTrianglesArrayType:
624 return AddRaytraceTriangleArray (theArray, theFirstVert, theVertOffset, theVertNum, theMatID);
626 case TelQuadranglesArrayType:
627 return AddRaytraceQuadrangleArray (theArray, theFirstVert, theVertOffset, theVertNum, theMatID);
629 case TelTriangleFansArrayType:
630 return AddRaytraceTriangleFanArray (theArray, theFirstVert, theVertOffset, theVertNum, theMatID);
632 case TelTriangleStripsArrayType:
633 return AddRaytraceTriangleStripArray (theArray, theFirstVert, theVertOffset, theVertNum, theMatID);
635 case TelQuadrangleStripsArrayType:
636 return AddRaytraceQuadrangleStripArray (theArray, theFirstVert, theVertOffset, theVertNum, theMatID);
638 case TelPolygonsArrayType:
639 return AddRaytracePolygonArray (theArray, theFirstVert, theVertOffset, theVertNum, theMatID);
642 return Standard_False;
645 // =======================================================================
646 // function : AddRaytraceTriangleArray
647 // purpose : Adds OpenGL triangle array to ray-traced scene geometry
648 // =======================================================================
649 Standard_Boolean OpenGl_Workspace::AddRaytraceTriangleArray (const CALL_DEF_PARRAY* theArray,
656 return Standard_True;
658 if (theArray->num_edges > 0)
660 for (int aVert = theVertOffset; aVert < theVertOffset + theVertNum - 2; aVert += 3)
662 myRaytraceSceneData.Triangles.push_back (OpenGl_RTVec4i (theFirstVert + theArray->edges[aVert + 0],
663 theFirstVert + theArray->edges[aVert + 1],
664 theFirstVert + theArray->edges[aVert + 2],
670 for (int aVert = theVertOffset; aVert < theVertOffset + theVertNum - 2; aVert += 3)
672 myRaytraceSceneData.Triangles.push_back (OpenGl_RTVec4i (theFirstVert + aVert + 0,
673 theFirstVert + aVert + 1,
674 theFirstVert + aVert + 2,
679 return Standard_True;
682 // =======================================================================
683 // function : AddRaytraceTriangleFanArray
684 // purpose : Adds OpenGL triangle fan array to ray-traced scene geometry
685 // =======================================================================
686 Standard_Boolean OpenGl_Workspace::AddRaytraceTriangleFanArray (const CALL_DEF_PARRAY* theArray,
693 return Standard_True;
695 if (theArray->num_edges > 0)
697 for (int aVert = theVertOffset; aVert < theVertOffset + theVertNum - 2; ++aVert)
699 myRaytraceSceneData.Triangles.push_back (OpenGl_RTVec4i (theFirstVert + theArray->edges[theVertOffset],
700 theFirstVert + theArray->edges[aVert + 1],
701 theFirstVert + theArray->edges[aVert + 2],
707 for (int aVert = theVertOffset; aVert < theVertOffset + theVertNum - 2; ++aVert)
709 myRaytraceSceneData.Triangles.push_back (OpenGl_RTVec4i (theFirstVert + theVertOffset,
710 theFirstVert + aVert + 1,
711 theFirstVert + aVert + 2,
716 return Standard_True;
719 // =======================================================================
720 // function : AddRaytraceTriangleStripArray
721 // purpose : Adds OpenGL triangle strip array to ray-traced scene geometry
722 // =======================================================================
723 Standard_Boolean OpenGl_Workspace::AddRaytraceTriangleStripArray (const CALL_DEF_PARRAY* theArray,
730 return Standard_True;
732 if (theArray->num_edges > 0)
734 myRaytraceSceneData.Triangles.push_back (OpenGl_RTVec4i (
735 theFirstVert + theArray->edges[theVertOffset + 0],
736 theFirstVert + theArray->edges[theVertOffset + 1],
737 theFirstVert + theArray->edges[theVertOffset + 2],
740 for (int aVert = theVertOffset + 1, aTriNum = 1; aVert < theVertOffset + theVertNum - 2; ++aVert, ++aTriNum)
742 myRaytraceSceneData.Triangles.push_back (OpenGl_RTVec4i (
743 theFirstVert + theArray->edges[aVert + (aTriNum % 2) ? 1 : 0],
744 theFirstVert + theArray->edges[aVert + (aTriNum % 2) ? 0 : 1],
745 theFirstVert + theArray->edges[aVert + 2],
751 myRaytraceSceneData.Triangles.push_back (OpenGl_RTVec4i (theFirstVert + theVertOffset + 0,
752 theFirstVert + theVertOffset + 1,
753 theFirstVert + theVertOffset + 2,
756 for (int aVert = theVertOffset + 1, aTriNum = 1; aVert < theVertOffset + theVertNum - 2; ++aVert, ++aTriNum)
758 myRaytraceSceneData.Triangles.push_back (OpenGl_RTVec4i (theFirstVert + aVert + ( aTriNum % 2 ) ? 1 : 0,
759 theFirstVert + aVert + ( aTriNum % 2 ) ? 0 : 1,
760 theFirstVert + aVert + 2,
765 return Standard_True;
768 // =======================================================================
769 // function : AddRaytraceQuadrangleArray
770 // purpose : Adds OpenGL quad array to ray-traced scene geometry
771 // =======================================================================
772 Standard_Boolean OpenGl_Workspace::AddRaytraceQuadrangleArray (const CALL_DEF_PARRAY* theArray,
779 return Standard_True;
781 if (theArray->num_edges > 0)
783 for (int aVert = theVertOffset; aVert < theVertOffset + theVertNum - 3; aVert += 4)
785 myRaytraceSceneData.Triangles.push_back (OpenGl_RTVec4i (theFirstVert + theArray->edges[aVert + 0],
786 theFirstVert + theArray->edges[aVert + 1],
787 theFirstVert + theArray->edges[aVert + 2],
790 myRaytraceSceneData.Triangles.push_back (OpenGl_RTVec4i (theFirstVert + theArray->edges[aVert + 0],
791 theFirstVert + theArray->edges[aVert + 2],
792 theFirstVert + theArray->edges[aVert + 3],
798 for (int aVert = theVertOffset; aVert < theVertOffset + theVertNum - 3; aVert += 4)
800 myRaytraceSceneData.Triangles.push_back (OpenGl_RTVec4i (theFirstVert + aVert + 0,
801 theFirstVert + aVert + 1,
802 theFirstVert + aVert + 2,
805 myRaytraceSceneData.Triangles.push_back (OpenGl_RTVec4i (theFirstVert + aVert + 0,
806 theFirstVert + aVert + 2,
807 theFirstVert + aVert + 3,
812 return Standard_True;
815 // =======================================================================
816 // function : AddRaytraceQuadrangleStripArray
817 // purpose : Adds OpenGL quad strip array to ray-traced scene geometry
818 // =======================================================================
819 Standard_Boolean OpenGl_Workspace::AddRaytraceQuadrangleStripArray (const CALL_DEF_PARRAY* theArray,
826 return Standard_True;
828 if (theArray->num_edges > 0)
830 myRaytraceSceneData.Triangles.push_back (OpenGl_RTVec4i (
831 theFirstVert + theArray->edges[theVertOffset + 0],
832 theFirstVert + theArray->edges[theVertOffset + 1],
833 theFirstVert + theArray->edges[theVertOffset + 2],
836 myRaytraceSceneData.Triangles.push_back (OpenGl_RTVec4i (
837 theFirstVert + theArray->edges[theVertOffset + 1],
838 theFirstVert + theArray->edges[theVertOffset + 3],
839 theFirstVert + theArray->edges[theVertOffset + 2],
842 for (int aVert = theVertOffset + 2; aVert < theVertOffset + theVertNum - 3; aVert += 2)
844 myRaytraceSceneData.Triangles.push_back (OpenGl_RTVec4i (
845 theFirstVert + theArray->edges[aVert + 0],
846 theFirstVert + theArray->edges[aVert + 1],
847 theFirstVert + theArray->edges[aVert + 2],
850 myRaytraceSceneData.Triangles.push_back (OpenGl_RTVec4i (
851 theFirstVert + theArray->edges[aVert + 1],
852 theFirstVert + theArray->edges[aVert + 3],
853 theFirstVert + theArray->edges[aVert + 2],
859 myRaytraceSceneData.Triangles.push_back (OpenGl_RTVec4i (theFirstVert + 0,
864 myRaytraceSceneData.Triangles.push_back (OpenGl_RTVec4i (theFirstVert + 1,
869 for (int aVert = theVertOffset + 2; aVert < theVertOffset + theVertNum - 3; aVert += 2)
871 myRaytraceSceneData.Triangles.push_back (OpenGl_RTVec4i (theFirstVert + aVert + 0,
872 theFirstVert + aVert + 1,
873 theFirstVert + aVert + 2,
876 myRaytraceSceneData.Triangles.push_back (OpenGl_RTVec4i (theFirstVert + aVert + 1,
877 theFirstVert + aVert + 3,
878 theFirstVert + aVert + 2,
883 return Standard_True;
886 // =======================================================================
887 // function : AddRaytracePolygonArray
888 // purpose : Adds OpenGL polygon array to ray-traced scene geometry
889 // =======================================================================
890 Standard_Boolean OpenGl_Workspace::AddRaytracePolygonArray (const CALL_DEF_PARRAY* theArray,
896 if (theArray->num_vertexs < 3)
897 return Standard_True;
899 if (theArray->edges != NULL)
901 for (int aVert = theVertOffset; aVert < theVertOffset + theVertNum - 2; ++aVert)
903 myRaytraceSceneData.Triangles.push_back (OpenGl_RTVec4i (theFirstVert + theArray->edges[theVertOffset],
904 theFirstVert + theArray->edges[aVert + 1],
905 theFirstVert + theArray->edges[aVert + 2],
911 for (int aVert = theVertOffset; aVert < theVertOffset + theVertNum - 2; ++aVert)
913 myRaytraceSceneData.Triangles.push_back (OpenGl_RTVec4i (theFirstVert + theVertOffset,
914 theFirstVert + aVert + 1,
915 theFirstVert + aVert + 2,
920 return Standard_True;
923 // =======================================================================
924 // function : UpdateRaytraceLightSources
925 // purpose : Updates 3D scene light sources for ray-tracing
926 // =======================================================================
927 Standard_Boolean OpenGl_Workspace::UpdateRaytraceLightSources (const GLdouble theInvModelView[16])
929 myRaytraceSceneData.LightSources.clear();
931 OpenGl_ListOfLight::Iterator anItl (myView->LightList());
933 OpenGl_RTVec4f aAmbient (0.f, 0.f, 0.f, 0.f);
935 for (; anItl.More(); anItl.Next())
937 const OpenGl_Light &aLight = anItl.Value();
939 if (aLight.type == TLightAmbient)
941 aAmbient += OpenGl_RTVec4f (aLight.col.rgb[0],
948 OpenGl_RTVec4f aDiffuse (aLight.col.rgb[0],
953 OpenGl_RTVec4f aPosition (-aLight.dir[0],
958 if (aLight.type != TLightDirectional)
960 aPosition = OpenGl_RTVec4f (aLight.pos[0],
966 if (aLight.HeadLight)
968 aPosition = MatVecMult (theInvModelView, aPosition);
971 myRaytraceSceneData.LightSources.push_back (OpenGl_RaytraceLight (aDiffuse, aPosition));
974 if (myRaytraceSceneData.LightSources.size() > 0)
976 myRaytraceSceneData.LightSources.front().Ambient += aAmbient;
980 myRaytraceSceneData.LightSources.push_back (OpenGl_RaytraceLight (OpenGl_RTVec4f (aAmbient.xyz(), -1.0f)));
983 cl_int anError = CL_SUCCESS;
985 if (myRaytraceLightSourceBuffer != NULL)
986 clReleaseMemObject (myRaytraceLightSourceBuffer);
988 const size_t myLightBufferSize = myRaytraceSceneData.LightSources.size() > 0
989 ? myRaytraceSceneData.LightSources.size()
992 myRaytraceLightSourceBuffer = clCreateBuffer (myComputeContext, CL_MEM_READ_ONLY,
993 myLightBufferSize * sizeof(OpenGl_RaytraceLight),
996 if (myRaytraceSceneData.LightSources.size() > 0)
998 const void* aDataPtr = myRaytraceSceneData.LightSources.front().Packed();
999 anError |= clEnqueueWriteBuffer (myRaytraceQueue, myRaytraceLightSourceBuffer, CL_TRUE, 0,
1000 myLightBufferSize * sizeof(OpenGl_RaytraceLight), aDataPtr,
1004 #ifdef RAY_TRACE_PRINT_INFO
1005 if (anError != CL_SUCCESS)
1007 std::cout << "Error! Failed to set light sources!";
1009 return Standard_False;
1013 return Standard_True;
1016 // =======================================================================
1017 // function : CheckOpenCL
1018 // purpose : Checks OpenCL dynamic library availability
1019 // =======================================================================
1020 Standard_Boolean CheckOpenCL()
1022 #if defined ( _WIN32 )
1026 cl_uint aNbPlatforms;
1027 clGetPlatformIDs (0, NULL, &aNbPlatforms);
1029 __except (EXCEPTION_EXECUTE_HANDLER)
1031 return Standard_False;
1036 return Standard_True;
1039 // =======================================================================
1040 // function : InitOpenCL
1041 // purpose : Initializes OpenCL objects
1042 // =======================================================================
1043 Standard_Boolean OpenGl_Workspace::InitOpenCL()
1045 if (myComputeInitStatus != OpenGl_CLIS_NONE)
1047 return myComputeInitStatus == OpenGl_CLIS_INIT;
1052 myComputeInitStatus = OpenGl_CLIS_FAIL; // fail to load OpenCL library
1053 myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
1054 GL_DEBUG_TYPE_ERROR_ARB,
1056 GL_DEBUG_SEVERITY_HIGH_ARB,
1057 "Failed to load OpenCL dynamic library!");
1058 return Standard_False;
1061 // Obtain the list of platforms available
1062 cl_uint aNbPlatforms = 0;
1063 cl_int anError = clGetPlatformIDs (0, NULL, &aNbPlatforms);
1064 cl_platform_id* aPlatforms = (cl_platform_id* )alloca (aNbPlatforms * sizeof(cl_platform_id));
1065 anError |= clGetPlatformIDs (aNbPlatforms, aPlatforms, NULL);
1066 if (anError != CL_SUCCESS
1067 || aNbPlatforms == 0)
1069 myComputeInitStatus = OpenGl_CLIS_FAIL;
1070 myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
1071 GL_DEBUG_TYPE_ERROR_ARB,
1073 GL_DEBUG_SEVERITY_HIGH_ARB,
1074 "No any OpenCL platform installed!");
1075 return Standard_False;
1078 // Note: We try to find NVIDIA or AMD platforms with GPU devices!
1079 cl_platform_id aPrefPlatform = NULL;
1080 for (cl_uint aPlatIter = 0; aPlatIter < aNbPlatforms; ++aPlatIter)
1083 anError = clGetPlatformInfo (aPlatforms[aPlatIter], CL_PLATFORM_NAME,
1084 sizeof(aName), aName, NULL);
1085 if (anError != CL_SUCCESS)
1090 if (strncmp (aName, "NVIDIA", strlen ("NVIDIA")) == 0)
1092 aPrefPlatform = aPlatforms[aPlatIter];
1094 // Use optimizations for NVIDIA GPUs
1095 myIsAmdComputePlatform = Standard_False;
1097 else if (strncmp (aName, "AMD", strlen ("AMD")) == 0)
1099 aPrefPlatform = (aPrefPlatform == NULL)
1100 ? aPlatforms[aPlatIter]
1103 // Use optimizations for ATI/AMD platform
1104 myIsAmdComputePlatform = Standard_True;
1108 if (aPrefPlatform == NULL)
1110 aPrefPlatform = aPlatforms[0];
1113 // Obtain the list of devices available in the selected platform
1114 cl_uint aNbDevices = 0;
1115 anError = clGetDeviceIDs (aPrefPlatform, CL_DEVICE_TYPE_GPU,
1116 0, NULL, &aNbDevices);
1118 cl_device_id* aDevices = (cl_device_id* )alloca (aNbDevices * sizeof(cl_device_id));
1119 anError |= clGetDeviceIDs (aPrefPlatform, CL_DEVICE_TYPE_GPU,
1120 aNbDevices, aDevices, NULL);
1121 if (anError != CL_SUCCESS)
1123 myComputeInitStatus = OpenGl_CLIS_FAIL;
1124 myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
1125 GL_DEBUG_TYPE_ERROR_ARB,
1127 GL_DEBUG_SEVERITY_HIGH_ARB,
1128 "Failed to get OpenCL GPU device!");
1129 return Standard_False;
1132 // Note: Simply get first available GPU
1133 cl_device_id aDevice = aDevices[0];
1135 // detect old contexts
1136 char aVerClStr[256];
1137 clGetDeviceInfo (aDevice, CL_DEVICE_VERSION,
1138 sizeof(aVerClStr), aVerClStr, NULL);
1139 aVerClStr[strlen ("OpenCL 1.0")] = '\0';
1140 const bool isVer10 = strncmp (aVerClStr, "OpenCL 1.0", strlen ("OpenCL 1.0")) == 0;
1142 // Create OpenCL context
1143 cl_context_properties aCtxProp[] =
1145 #if defined(__APPLE__) && !defined(MACOSX_USE_GLX)
1146 CL_CONTEXT_PROPERTY_USE_CGL_SHAREGROUP_APPLE,
1147 (cl_context_properties )CGLGetShareGroup (CGLGetCurrentContext()),
1148 #elif defined(_WIN32)
1149 CL_CONTEXT_PLATFORM, (cl_context_properties )aPrefPlatform,
1150 CL_GL_CONTEXT_KHR, (cl_context_properties )wglGetCurrentContext(),
1151 CL_WGL_HDC_KHR, (cl_context_properties )wglGetCurrentDC(),
1153 CL_GL_CONTEXT_KHR, (cl_context_properties )glXGetCurrentContext(),
1154 CL_GLX_DISPLAY_KHR, (cl_context_properties )glXGetCurrentDisplay(),
1155 CL_CONTEXT_PLATFORM, (cl_context_properties )aPrefPlatform,
1160 myComputeContext = clCreateContext (aCtxProp,
1161 #if defined(__APPLE__) && !defined(MACOSX_USE_GLX)
1162 0, NULL, // device will be taken from GL context
1166 NULL, NULL, &anError);
1167 if (anError != CL_SUCCESS)
1169 myComputeInitStatus = OpenGl_CLIS_FAIL;
1170 myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
1171 GL_DEBUG_TYPE_ERROR_ARB,
1173 GL_DEBUG_SEVERITY_HIGH_ARB,
1174 "Failed to initialize OpenCL context!");
1175 return Standard_False;
1178 // Create OpenCL program
1179 const char* aSources[] =
1181 isVer10 ? "#define M_PI_F ( float )( 3.14159265359f )\n" : "",
1182 THE_RAY_TRACE_OPENCL_SOURCE
1184 myRaytraceProgram = clCreateProgramWithSource (myComputeContext, 2,
1185 aSources, NULL, &anError);
1186 if (anError != CL_SUCCESS)
1188 myComputeInitStatus = OpenGl_CLIS_FAIL;
1189 myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
1190 GL_DEBUG_TYPE_ERROR_ARB,
1192 GL_DEBUG_SEVERITY_HIGH_ARB,
1193 "Failed to create OpenCL ray-tracing program!");
1194 return Standard_False;
1197 anError = clBuildProgram (myRaytraceProgram, 0,
1198 NULL, NULL, NULL, NULL);
1202 cl_int aResult = clGetProgramBuildInfo (myRaytraceProgram, aDevice,
1203 CL_PROGRAM_BUILD_LOG, 0, NULL, &aLogLen);
1205 char* aBuildLog = (char* )alloca (aLogLen);
1206 aResult |= clGetProgramBuildInfo (myRaytraceProgram, aDevice,
1207 CL_PROGRAM_BUILD_LOG, aLogLen, aBuildLog, NULL);
1208 if (aResult == CL_SUCCESS)
1210 if (anError != CL_SUCCESS)
1212 myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
1213 GL_DEBUG_TYPE_ERROR_ARB,
1215 GL_DEBUG_SEVERITY_HIGH_ARB,
1220 #ifdef RAY_TRACE_PRINT_INFO
1221 std::cout << aBuildLog << std::endl;
1227 if (anError != CL_SUCCESS)
1229 return Standard_False;
1232 // Create OpenCL ray tracing kernels
1233 myRaytraceRenderKernel = clCreateKernel (myRaytraceProgram, "Main", &anError);
1234 if (anError != CL_SUCCESS)
1236 myComputeInitStatus = OpenGl_CLIS_FAIL;
1237 myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
1238 GL_DEBUG_TYPE_ERROR_ARB,
1240 GL_DEBUG_SEVERITY_HIGH_ARB,
1241 "Failed to create OpenCL ray-tracing kernel!");
1242 return Standard_False;
1245 myRaytraceSmoothKernel = clCreateKernel (myRaytraceProgram, "MainAntialiased", &anError);
1246 if (anError != CL_SUCCESS)
1248 myComputeInitStatus = OpenGl_CLIS_FAIL;
1249 myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
1250 GL_DEBUG_TYPE_ERROR_ARB,
1252 GL_DEBUG_SEVERITY_HIGH_ARB,
1253 "Failed to create OpenCL ray-tracing kernel!");
1254 return Standard_False;
1257 // Create OpenCL command queue
1258 // Note: For profiling set CL_QUEUE_PROFILING_ENABLE
1259 cl_command_queue_properties aProps = CL_QUEUE_PROFILING_ENABLE;
1261 myRaytraceQueue = clCreateCommandQueue (myComputeContext, aDevice, aProps, &anError);
1262 if (anError != CL_SUCCESS)
1264 myComputeInitStatus = OpenGl_CLIS_FAIL;
1265 myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
1266 GL_DEBUG_TYPE_ERROR_ARB,
1268 GL_DEBUG_SEVERITY_HIGH_ARB,
1269 "Failed to create OpenCL command queue!");
1271 return Standard_False;
1274 myComputeInitStatus = OpenGl_CLIS_INIT; // initialized in normal way
1275 return Standard_True;
1278 // =======================================================================
1279 // function : GetOpenClDeviceInfo
1280 // purpose : Returns information about device used for computations
1281 // =======================================================================
1282 Standard_Boolean OpenGl_Workspace::GetOpenClDeviceInfo (NCollection_DataMap<TCollection_AsciiString,
1283 TCollection_AsciiString>& theInfo) const
1286 if (myComputeContext == NULL)
1288 return Standard_False;
1291 size_t aDevicesSize = 0;
1292 cl_int anError = clGetContextInfo (myComputeContext, CL_CONTEXT_DEVICES, 0, NULL, &aDevicesSize);
1293 cl_device_id* aDevices = (cl_device_id* )alloca (aDevicesSize);
1294 anError |= clGetContextInfo (myComputeContext, CL_CONTEXT_DEVICES, aDevicesSize, aDevices, NULL);
1295 if (anError != CL_SUCCESS)
1297 return Standard_False;
1300 char aDeviceName[256];
1301 anError |= clGetDeviceInfo (aDevices[0], CL_DEVICE_NAME, sizeof(aDeviceName), aDeviceName, NULL);
1302 theInfo.Bind ("Name", aDeviceName);
1304 char aDeviceVendor[256];
1305 anError |= clGetDeviceInfo (aDevices[0], CL_DEVICE_VENDOR, sizeof(aDeviceVendor), aDeviceVendor, NULL);
1306 theInfo.Bind ("Vendor", aDeviceVendor);
1308 cl_device_type aDeviceType;
1309 anError |= clGetDeviceInfo (aDevices[0], CL_DEVICE_TYPE, sizeof(aDeviceType), &aDeviceType, NULL);
1310 theInfo.Bind ("Type", aDeviceType == CL_DEVICE_TYPE_GPU ? "GPU" : "CPU");
1311 return Standard_True;
1314 // =======================================================================
1315 // function : ReleaseOpenCL
1316 // purpose : Releases resources of OpenCL objects
1317 // =======================================================================
1318 void OpenGl_Workspace::ReleaseOpenCL()
1320 clReleaseKernel (myRaytraceRenderKernel);
1321 clReleaseKernel (myRaytraceSmoothKernel);
1323 clReleaseProgram (myRaytraceProgram);
1324 clReleaseCommandQueue (myRaytraceQueue);
1326 clReleaseMemObject (myRaytraceOutputImage);
1327 clReleaseMemObject (myRaytraceEnvironment);
1328 clReleaseMemObject (myRaytraceOutputImageSmooth);
1330 clReleaseMemObject (myRaytraceVertexBuffer);
1331 clReleaseMemObject (myRaytraceNormalBuffer);
1332 clReleaseMemObject (myRaytraceTriangleBuffer);
1334 clReleaseMemObject (myRaytraceMaterialBuffer);
1335 clReleaseMemObject (myRaytraceLightSourceBuffer);
1337 clReleaseMemObject (myRaytraceNodeMinPointBuffer);
1338 clReleaseMemObject (myRaytraceNodeMaxPointBuffer);
1339 clReleaseMemObject (myRaytraceNodeDataRcrdBuffer);
1341 clReleaseContext (myComputeContext);
1343 if (glIsTexture (*myRaytraceOutputTexture))
1344 glDeleteTextures (2, myRaytraceOutputTexture);
1347 // =======================================================================
1348 // function : ResizeRaytraceOutputBuffer
1349 // purpose : Resizes OpenCL output image
1350 // =======================================================================
1351 Standard_Boolean OpenGl_Workspace::ResizeRaytraceOutputBuffer (const cl_int theSizeX,
1352 const cl_int theSizeY)
1354 if (myComputeContext == NULL)
1356 return Standard_False;
1359 bool toResize = true;
1362 if (*myRaytraceOutputTexture != 0)
1364 if (!myGlContext->IsGlGreaterEqual (2, 1))
1366 return Standard_False;
1369 glBindTexture (GL_TEXTURE_RECTANGLE, *myRaytraceOutputTexture);
1371 glGetTexLevelParameteriv (GL_TEXTURE_RECTANGLE, 0, GL_TEXTURE_WIDTH, &aSizeX);
1372 glGetTexLevelParameteriv (GL_TEXTURE_RECTANGLE, 0, GL_TEXTURE_HEIGHT, &aSizeY);
1374 toResize = (aSizeX != theSizeX) || (aSizeY != theSizeY);
1377 glDeleteTextures (2, myRaytraceOutputTexture);
1382 return Standard_True;
1385 glGenTextures (2, myRaytraceOutputTexture);
1386 for (int aTexIter = 0; aTexIter < 2; ++aTexIter)
1388 glBindTexture (GL_TEXTURE_RECTANGLE, myRaytraceOutputTexture[aTexIter]);
1390 glTexParameteri (GL_TEXTURE_RECTANGLE, GL_TEXTURE_WRAP_S, GL_CLAMP);
1391 glTexParameteri (GL_TEXTURE_RECTANGLE, GL_TEXTURE_WRAP_T, GL_CLAMP);
1392 glTexParameteri (GL_TEXTURE_RECTANGLE, GL_TEXTURE_WRAP_R, GL_CLAMP);
1394 glTexParameteri (GL_TEXTURE_RECTANGLE, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
1395 glTexParameteri (GL_TEXTURE_RECTANGLE, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
1397 glTexImage2D (GL_TEXTURE_RECTANGLE, 0, GL_RGBA32F,
1398 theSizeX, theSizeY, 0,
1399 GL_RGBA, GL_FLOAT, NULL);
1402 cl_int anError = CL_SUCCESS;
1404 if (myRaytraceOutputImage != NULL)
1406 clReleaseMemObject (myRaytraceOutputImage);
1408 if (myRaytraceOutputImageSmooth != NULL)
1410 clReleaseMemObject (myRaytraceOutputImageSmooth);
1413 myRaytraceOutputImage = clCreateFromGLTexture2D (myComputeContext, CL_MEM_READ_WRITE,
1414 GL_TEXTURE_RECTANGLE, 0,
1415 myRaytraceOutputTexture[0], &anError);
1416 if (anError != CL_SUCCESS)
1418 #ifdef RAY_TRACE_PRINT_INFO
1419 std::cout << "Error! Failed to create output image!" << std::endl;
1421 return Standard_False;
1424 myRaytraceOutputImageSmooth = clCreateFromGLTexture2D (myComputeContext, CL_MEM_READ_WRITE,
1425 GL_TEXTURE_RECTANGLE, 0,
1426 myRaytraceOutputTexture[1], &anError);
1427 if (anError != CL_SUCCESS)
1429 #ifdef RAY_TRACE_PRINT_INFO
1430 std::cout << "Error! Failed to create anti-aliased output image!" << std::endl;
1432 return Standard_False;
1435 return Standard_True;
1438 // =======================================================================
1439 // function : WriteRaytraceSceneToDevice
1440 // purpose : Writes scene geometry to OpenCl device
1441 // =======================================================================
1442 Standard_Boolean OpenGl_Workspace::WriteRaytraceSceneToDevice()
1444 if (myComputeContext == NULL)
1445 return Standard_False;
1447 cl_int anError = CL_SUCCESS;
1449 if (myRaytraceNormalBuffer != NULL)
1450 anError |= clReleaseMemObject (myRaytraceNormalBuffer);
1452 if (myRaytraceVertexBuffer != NULL)
1453 anError |= clReleaseMemObject (myRaytraceVertexBuffer);
1455 if (myRaytraceTriangleBuffer != NULL)
1456 anError |= clReleaseMemObject (myRaytraceTriangleBuffer);
1458 if (myRaytraceNodeMinPointBuffer != NULL)
1459 anError |= clReleaseMemObject (myRaytraceNodeMinPointBuffer);
1461 if (myRaytraceNodeMaxPointBuffer != NULL)
1462 anError |= clReleaseMemObject (myRaytraceNodeMaxPointBuffer);
1464 if (myRaytraceNodeDataRcrdBuffer != NULL)
1465 anError |= clReleaseMemObject (myRaytraceNodeDataRcrdBuffer);
1467 if (myRaytraceMaterialBuffer != NULL)
1468 anError |= clReleaseMemObject (myRaytraceMaterialBuffer);
1470 if (anError != CL_SUCCESS)
1472 #ifdef RAY_TRACE_PRINT_INFO
1473 std::cout << "Error! Failed to release OpenCL scene buffers!" << std::endl;
1475 return Standard_False;
1478 // Create geometry buffers
1479 cl_int anErrorTemp = CL_SUCCESS;
1480 const size_t myVertexBufferSize = myRaytraceSceneData.Vertices.size() > 0
1481 ? myRaytraceSceneData.Vertices.size() : 1;
1483 myRaytraceVertexBuffer = clCreateBuffer (myComputeContext, CL_MEM_READ_ONLY,
1484 myVertexBufferSize * sizeof(cl_float4), NULL, &anErrorTemp);
1485 anError |= anErrorTemp;
1487 const size_t myNormalBufferSize = myRaytraceSceneData.Normals.size() > 0
1488 ? myRaytraceSceneData.Normals.size() : 1;
1489 myRaytraceNormalBuffer = clCreateBuffer (myComputeContext, CL_MEM_READ_ONLY,
1490 myNormalBufferSize * sizeof(cl_float4), NULL, &anErrorTemp);
1491 anError |= anErrorTemp;
1493 const size_t myTriangleBufferSize = myRaytraceSceneData.Triangles.size() > 0
1494 ? myRaytraceSceneData.Triangles.size() : 1;
1495 myRaytraceTriangleBuffer = clCreateBuffer (myComputeContext, CL_MEM_READ_ONLY,
1496 myTriangleBufferSize * sizeof(cl_int4), NULL, &anErrorTemp);
1497 anError |= anErrorTemp;
1498 if (anError != CL_SUCCESS)
1500 #ifdef RAY_TRACE_PRINT_INFO
1501 std::cout << "Error! Failed to create OpenCL geometry buffers!" << std::endl;
1503 return Standard_False;
1506 // Create material buffer
1507 const size_t myMaterialBufferSize = myRaytraceSceneData.Materials.size() > 0
1508 ? myRaytraceSceneData.Materials.size() : 1;
1509 myRaytraceMaterialBuffer = clCreateBuffer (myComputeContext, CL_MEM_READ_ONLY,
1510 myMaterialBufferSize * sizeof(OpenGl_RaytraceMaterial), NULL,
1512 if (anErrorTemp != CL_SUCCESS)
1514 #ifdef RAY_TRACE_PRINT_INFO
1515 std::cout << "Error! Failed to create OpenCL material buffer!" << std::endl;
1517 return Standard_False;
1520 // Create BVH buffers
1521 OpenGl_BVH aTree = myBVHBuilder.Tree();
1522 const size_t myNodeMinPointBufferSize = aTree.MinPointBuffer().size() > 0
1523 ? aTree.MinPointBuffer().size() : 1;
1524 myRaytraceNodeMinPointBuffer = clCreateBuffer (myComputeContext, CL_MEM_READ_ONLY,
1525 myNodeMinPointBufferSize * sizeof(cl_float4), NULL,
1527 anError |= anErrorTemp;
1529 const size_t myNodeMaxPointBufferSize = aTree.MaxPointBuffer().size() > 0
1530 ? aTree.MaxPointBuffer().size() : 1;
1531 myRaytraceNodeMaxPointBuffer = clCreateBuffer (myComputeContext, CL_MEM_READ_ONLY,
1532 myNodeMaxPointBufferSize * sizeof(cl_float4), NULL,
1534 anError |= anErrorTemp;
1536 const size_t myNodeDataRecordBufferSize = aTree.DataRcrdBuffer().size() > 0
1537 ? aTree.DataRcrdBuffer().size() : 1;
1538 myRaytraceNodeDataRcrdBuffer = clCreateBuffer (myComputeContext, CL_MEM_READ_ONLY,
1539 myNodeDataRecordBufferSize * sizeof(cl_int4), NULL,
1541 anError |= anErrorTemp;
1542 if (anError != CL_SUCCESS)
1544 #ifdef RAY_TRACE_PRINT_INFO
1545 std::cout << "Error! Failed to create OpenCL BVH buffers!" << std::endl;
1547 return Standard_False;
1550 // Write scene geometry buffers
1551 if (myRaytraceSceneData.Triangles.size() > 0)
1553 anError |= clEnqueueWriteBuffer (myRaytraceQueue, myRaytraceVertexBuffer, CL_FALSE,
1554 0, myRaytraceSceneData.Vertices.size() * sizeof(cl_float4),
1555 &myRaytraceSceneData.Vertices.front(),
1557 anError |= clEnqueueWriteBuffer (myRaytraceQueue, myRaytraceNormalBuffer, CL_FALSE,
1558 0, myRaytraceSceneData.Normals.size() * sizeof(cl_float4),
1559 &myRaytraceSceneData.Normals.front(),
1561 anError |= clEnqueueWriteBuffer (myRaytraceQueue, myRaytraceTriangleBuffer, CL_FALSE,
1562 0, myRaytraceSceneData.Triangles.size() * sizeof(cl_int4),
1563 &myRaytraceSceneData.Triangles.front(),
1565 if (anError != CL_SUCCESS)
1567 #ifdef RAY_TRACE_PRINT_INFO
1568 std::cout << "Error! Failed to write OpenCL geometry buffers!" << std::endl;
1570 return Standard_False;
1574 // Write BVH buffers
1575 if (aTree.DataRcrdBuffer().size() > 0)
1577 anError |= clEnqueueWriteBuffer (myRaytraceQueue, myRaytraceNodeMinPointBuffer, CL_FALSE,
1578 0, aTree.MinPointBuffer().size() * sizeof(cl_float4),
1579 &aTree.MinPointBuffer().front(),
1581 anError |= clEnqueueWriteBuffer (myRaytraceQueue, myRaytraceNodeMaxPointBuffer, CL_FALSE,
1582 0, aTree.MaxPointBuffer().size() * sizeof(cl_float4),
1583 &aTree.MaxPointBuffer().front(),
1585 anError |= clEnqueueWriteBuffer (myRaytraceQueue, myRaytraceNodeDataRcrdBuffer, CL_FALSE,
1586 0, aTree.DataRcrdBuffer().size() * sizeof(cl_int4),
1587 &aTree.DataRcrdBuffer().front(),
1589 if (anError != CL_SUCCESS)
1591 #ifdef RAY_TRACE_PRINT_INFO
1592 std::cout << "Error! Failed to write OpenCL BVH buffers!" << std::endl;
1594 return Standard_False;
1598 // Write material buffers
1599 if (myRaytraceSceneData.Materials.size() > 0)
1601 const size_t aSize = myRaytraceSceneData.Materials.size();
1602 const void* aDataPtr = myRaytraceSceneData.Materials.front().Packed();
1604 anError |= clEnqueueWriteBuffer (myRaytraceQueue, myRaytraceMaterialBuffer, CL_FALSE,
1605 0, aSize * sizeof(OpenGl_RaytraceMaterial), aDataPtr,
1607 if (anError != CL_SUCCESS)
1609 #ifdef RAY_TRACE_PRINT_INFO
1610 std::cout << "Error! Failed to write OpenCL material buffer!" << std::endl;
1612 return Standard_False;
1616 anError |= clFinish (myRaytraceQueue);
1617 #ifdef RAY_TRACE_PRINT_INFO
1618 if (anError != CL_SUCCESS)
1619 std::cout << "Error! Failed to set scene data buffers!" << std::endl;
1622 if (anError == CL_SUCCESS)
1623 myIsRaytraceDataValid = myRaytraceSceneData.Triangles.size() > 0;
1625 #ifdef RAY_TRACE_PRINT_INFO
1627 float aMemUsed = static_cast<float> (
1628 myRaytraceSceneData.Materials.size()) * sizeof (OpenGl_RaytraceMaterial);
1630 aMemUsed += static_cast<float> (
1631 myRaytraceSceneData.Triangles.size() * sizeof (OpenGl_RTVec4i) +
1632 myRaytraceSceneData.Vertices.size() * sizeof (OpenGl_RTVec4f) +
1633 myRaytraceSceneData.Normals.size() * sizeof (OpenGl_RTVec4f));
1635 aMemUsed += static_cast<float> (
1636 aTree.MinPointBuffer().size() * sizeof (OpenGl_RTVec4f) +
1637 aTree.MaxPointBuffer().size() * sizeof (OpenGl_RTVec4f) +
1638 aTree.DataRcrdBuffer().size() * sizeof (OpenGl_RTVec4i));
1640 std::cout << "GPU memory used (Mb): " << aMemUsed / 1e6f << std::endl;
1644 myRaytraceSceneData.Clear();
1646 myBVHBuilder.CleanUp();
1648 return (CL_SUCCESS == anError);
1651 #define OPENCL_GROUP_SIZE_TEST_
1653 // =======================================================================
1654 // function : RunRaytraceOpenCLKernels
1655 // purpose : Runs OpenCL ray-tracing kernels
1656 // =======================================================================
1657 Standard_Boolean OpenGl_Workspace::RunRaytraceOpenCLKernels (const Graphic3d_CView& theCView,
1658 const GLfloat theOrigins[16],
1659 const GLfloat theDirects[16],
1663 if (myRaytraceRenderKernel == NULL || myRaytraceQueue == NULL)
1664 return Standard_False;
1666 ////////////////////////////////////////////////////////////
1667 // Set kernel arguments
1669 cl_uint anIndex = 0;
1672 anError = clSetKernelArg (myRaytraceRenderKernel, anIndex++,
1673 sizeof(cl_mem), &myRaytraceOutputImage);
1674 anError |= clSetKernelArg (myRaytraceRenderKernel, anIndex++,
1675 sizeof(cl_mem), &myRaytraceEnvironment);
1676 anError |= clSetKernelArg (myRaytraceRenderKernel, anIndex++,
1677 sizeof(cl_mem), &myRaytraceNodeMinPointBuffer);
1678 anError |= clSetKernelArg (myRaytraceRenderKernel, anIndex++,
1679 sizeof(cl_mem), &myRaytraceNodeMaxPointBuffer);
1680 anError |= clSetKernelArg (myRaytraceRenderKernel, anIndex++,
1681 sizeof(cl_mem), &myRaytraceNodeDataRcrdBuffer);
1682 anError |= clSetKernelArg (myRaytraceRenderKernel, anIndex++,
1683 sizeof(cl_mem), &myRaytraceLightSourceBuffer);
1684 anError |= clSetKernelArg (myRaytraceRenderKernel, anIndex++,
1685 sizeof(cl_mem), &myRaytraceMaterialBuffer);
1686 anError |= clSetKernelArg (myRaytraceRenderKernel, anIndex++,
1687 sizeof(cl_mem), &myRaytraceVertexBuffer);
1688 anError |= clSetKernelArg (myRaytraceRenderKernel, anIndex++,
1689 sizeof(cl_mem), &myRaytraceNormalBuffer);
1690 anError |= clSetKernelArg (myRaytraceRenderKernel, anIndex++,
1691 sizeof(cl_mem), &myRaytraceTriangleBuffer);
1693 anError |= clSetKernelArg (myRaytraceRenderKernel, anIndex++,
1694 sizeof(cl_float16), theOrigins);
1695 anError |= clSetKernelArg (myRaytraceRenderKernel, anIndex++,
1696 sizeof(cl_float16), theDirects);
1698 cl_int aLightCount = static_cast<cl_int> (myRaytraceSceneData.LightSources.size());
1700 anError |= clSetKernelArg (myRaytraceRenderKernel, anIndex++,
1701 sizeof(cl_int), &aLightCount);
1702 anError |= clSetKernelArg (myRaytraceRenderKernel, anIndex++,
1703 sizeof(cl_float), &myRaytraceSceneEpsilon);
1704 anError |= clSetKernelArg (myRaytraceRenderKernel, anIndex++,
1705 sizeof(cl_float), &myRaytraceSceneRadius);
1706 anError |= clSetKernelArg (myRaytraceRenderKernel, anIndex++,
1707 sizeof(cl_int), &theCView.IsShadowsEnabled);
1708 anError |= clSetKernelArg (myRaytraceRenderKernel, anIndex++,
1709 sizeof(cl_int), &theCView.IsReflectionsEnabled);
1710 anError |= clSetKernelArg (myRaytraceRenderKernel, anIndex++,
1711 sizeof(cl_int), &theSizeX);
1712 anError |= clSetKernelArg (myRaytraceRenderKernel, anIndex++,
1713 sizeof(cl_int), &theSizeY);
1714 if (anError != CL_SUCCESS)
1716 const TCollection_ExtendedString aMsg = "Error! Failed to set arguments of ray-tracing kernel!";
1717 myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
1718 GL_DEBUG_TYPE_ERROR_ARB,
1720 GL_DEBUG_SEVERITY_HIGH_ARB,
1722 return Standard_False;
1725 // Note: second-pass 'smoothing' kernel runs only if anti-aliasing is enabled
1726 if (theCView.IsAntialiasingEnabled)
1729 anError = clSetKernelArg (myRaytraceSmoothKernel, anIndex++,
1730 sizeof(cl_mem), &myRaytraceOutputImage);
1731 anError |= clSetKernelArg (myRaytraceSmoothKernel, anIndex++,
1732 sizeof(cl_mem), &myRaytraceOutputImageSmooth);
1733 anError |= clSetKernelArg (myRaytraceSmoothKernel, anIndex++,
1734 sizeof(cl_mem), &myRaytraceEnvironment);
1735 anError |= clSetKernelArg (myRaytraceSmoothKernel, anIndex++,
1736 sizeof(cl_mem), &myRaytraceNodeMinPointBuffer);
1737 anError |= clSetKernelArg (myRaytraceSmoothKernel, anIndex++,
1738 sizeof(cl_mem), &myRaytraceNodeMaxPointBuffer);
1739 anError |= clSetKernelArg (myRaytraceSmoothKernel, anIndex++,
1740 sizeof(cl_mem), &myRaytraceNodeDataRcrdBuffer);
1741 anError |= clSetKernelArg (myRaytraceSmoothKernel, anIndex++,
1742 sizeof(cl_mem), &myRaytraceLightSourceBuffer);
1743 anError |= clSetKernelArg (myRaytraceSmoothKernel, anIndex++,
1744 sizeof(cl_mem), &myRaytraceMaterialBuffer);
1745 anError |= clSetKernelArg (myRaytraceSmoothKernel, anIndex++,
1746 sizeof(cl_mem), &myRaytraceVertexBuffer);
1747 anError |= clSetKernelArg (myRaytraceSmoothKernel, anIndex++,
1748 sizeof(cl_mem), &myRaytraceNormalBuffer);
1749 anError |= clSetKernelArg (myRaytraceSmoothKernel, anIndex++,
1750 sizeof(cl_mem), &myRaytraceTriangleBuffer);
1752 anError |= clSetKernelArg (myRaytraceSmoothKernel, anIndex++,
1753 sizeof(cl_float16), theOrigins);
1754 anError |= clSetKernelArg (myRaytraceSmoothKernel, anIndex++,
1755 sizeof(cl_float16), theDirects);
1757 anError |= clSetKernelArg (myRaytraceSmoothKernel, anIndex++,
1758 sizeof(cl_int), &aLightCount);
1759 anError |= clSetKernelArg (myRaytraceSmoothKernel, anIndex++,
1760 sizeof(cl_float), &myRaytraceSceneEpsilon);
1761 anError |= clSetKernelArg (myRaytraceSmoothKernel, anIndex++,
1762 sizeof(cl_float), &myRaytraceSceneRadius);
1763 anError |= clSetKernelArg (myRaytraceSmoothKernel, anIndex++,
1764 sizeof(cl_int), &theCView.IsShadowsEnabled);
1765 anError |= clSetKernelArg (myRaytraceSmoothKernel, anIndex++,
1766 sizeof(cl_int), &theCView.IsReflectionsEnabled);
1767 anError |= clSetKernelArg (myRaytraceSmoothKernel, anIndex++,
1768 sizeof(cl_int), &theSizeX);
1769 anError |= clSetKernelArg (myRaytraceSmoothKernel, anIndex++,
1770 sizeof(cl_int), &theSizeY);
1771 if (anError != CL_SUCCESS)
1773 const TCollection_ExtendedString aMsg = "Error! Failed to set arguments of 'smoothing' kernel!";
1774 myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
1775 GL_DEBUG_TYPE_ERROR_ARB,
1777 GL_DEBUG_SEVERITY_HIGH_ARB,
1779 return Standard_False;
1784 size_t aLocSizeRender[] = { myIsAmdComputePlatform ? 2 : 4, 32 };
1786 #ifdef OPENCL_GROUP_SIZE_TEST
1787 for (size_t aLocX = 2; aLocX <= 32; aLocX <<= 1 )
1788 for (size_t aLocY = 2; aLocY <= 32; aLocY <<= 1 )
1791 #ifdef OPENCL_GROUP_SIZE_TEST
1792 aLocSizeRender[0] = aLocX;
1793 aLocSizeRender[1] = aLocY;
1796 size_t aWorkSizeX = theSizeX;
1797 if (aWorkSizeX % aLocSizeRender[0] != 0)
1798 aWorkSizeX += aLocSizeRender[0] - aWorkSizeX % aLocSizeRender[0];
1800 size_t aWokrSizeY = theSizeY;
1801 if (aWokrSizeY % aLocSizeRender[1] != 0 )
1802 aWokrSizeY += aLocSizeRender[1] - aWokrSizeY % aLocSizeRender[1];
1804 size_t aGlbSizeRender[] = { aWorkSizeX, aWokrSizeY };
1807 cl_event anEvent (NULL), anEventSmooth (NULL);
1808 anError = clEnqueueNDRangeKernel (myRaytraceQueue, myRaytraceRenderKernel,
1809 2, NULL, aGlbSizeRender, aLocSizeRender,
1811 if (anError != CL_SUCCESS)
1813 const TCollection_ExtendedString aMsg = "Error! Failed to execute the ray-tracing kernel!";
1814 myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
1815 GL_DEBUG_TYPE_ERROR_ARB,
1817 GL_DEBUG_SEVERITY_HIGH_ARB,
1819 return Standard_False;
1821 clWaitForEvents (1, &anEvent);
1823 if (theCView.IsAntialiasingEnabled)
1825 size_t aLocSizeSmooth[] = { myIsAmdComputePlatform ? 8 : 4,
1826 myIsAmdComputePlatform ? 8 : 32 };
1828 #ifdef OPENCL_GROUP_SIZE_TEST
1829 aLocSizeSmooth[0] = aLocX;
1830 aLocSizeSmooth[1] = aLocY;
1833 aWorkSizeX = theSizeX;
1834 if (aWorkSizeX % aLocSizeSmooth[0] != 0)
1835 aWorkSizeX += aLocSizeSmooth[0] - aWorkSizeX % aLocSizeSmooth[0];
1837 size_t aWokrSizeY = theSizeY;
1838 if (aWokrSizeY % aLocSizeSmooth[1] != 0 )
1839 aWokrSizeY += aLocSizeSmooth[1] - aWokrSizeY % aLocSizeSmooth[1];
1841 size_t aGlbSizeSmooth [] = { aWorkSizeX, aWokrSizeY };
1842 anError = clEnqueueNDRangeKernel (myRaytraceQueue, myRaytraceSmoothKernel,
1843 2, NULL, aGlbSizeSmooth, aLocSizeSmooth,
1844 0, NULL, &anEventSmooth);
1845 clWaitForEvents (1, &anEventSmooth);
1847 if (anError != CL_SUCCESS)
1849 const TCollection_ExtendedString aMsg = "Error! Failed to execute the 'smoothing' kernel!";
1850 myGlContext->PushMessage (GL_DEBUG_SOURCE_APPLICATION_ARB,
1851 GL_DEBUG_TYPE_ERROR_ARB,
1853 GL_DEBUG_SEVERITY_HIGH_ARB,
1855 return Standard_False;
1859 // Get the profiling data
1860 #if defined (RAY_TRACE_PRINT_INFO) || defined(OPENCL_GROUP_SIZE_TEST)
1862 cl_ulong aTimeStart,
1865 clGetEventProfilingInfo (anEvent, CL_PROFILING_COMMAND_START,
1866 sizeof(aTimeStart), &aTimeStart, NULL);
1867 clGetEventProfilingInfo (anEvent, CL_PROFILING_COMMAND_END,
1868 sizeof(aTimeFinal), &aTimeFinal, NULL);
1869 std::cout << "\tRender time (ms): " << ( aTimeFinal - aTimeStart ) / 1e6f << std::endl;
1871 if (theCView.IsAntialiasingEnabled)
1873 clGetEventProfilingInfo (anEventSmooth, CL_PROFILING_COMMAND_START,
1874 sizeof(aTimeStart), &aTimeStart, NULL);
1875 clGetEventProfilingInfo (anEventSmooth, CL_PROFILING_COMMAND_END,
1876 sizeof(aTimeFinal), &aTimeFinal, NULL);
1877 std::cout << "\tSmoothing time (ms): " << ( aTimeFinal - aTimeStart ) / 1e6f << std::endl;
1881 if (anEvent != NULL)
1882 clReleaseEvent (anEvent);
1884 if (anEventSmooth != NULL)
1885 clReleaseEvent (anEventSmooth);
1888 return Standard_True;
1891 // =======================================================================
1892 // function : ComputeInverseMatrix
1893 // purpose : Computes inversion of 4x4 floating-point matrix
1894 // =======================================================================
1895 template <typename T>
1896 void ComputeInverseMatrix (const T m[16], T inv[16])
1898 inv[ 0] = m[ 5] * (m[10] * m[15] - m[11] * m[14]) -
1899 m[ 9] * (m[ 6] * m[15] - m[ 7] * m[14]) -
1900 m[13] * (m[ 7] * m[10] - m[ 6] * m[11]);
1902 inv[ 1] = m[ 1] * (m[11] * m[14] - m[10] * m[15]) -
1903 m[ 9] * (m[ 3] * m[14] - m[ 2] * m[15]) -
1904 m[13] * (m[ 2] * m[11] - m[ 3] * m[10]);
1906 inv[ 2] = m[ 1] * (m[ 6] * m[15] - m[ 7] * m[14]) -
1907 m[ 5] * (m[ 2] * m[15] - m[ 3] * m[14]) -
1908 m[13] * (m[ 3] * m[ 6] - m[ 2] * m[ 7]);
1910 inv[ 3] = m[ 1] * (m[ 7] * m[10] - m[ 6] * m[11]) -
1911 m[ 5] * (m[ 3] * m[10] - m[ 2] * m[11]) -
1912 m[ 9] * (m[ 2] * m[ 7] - m[ 3] * m[ 6]);
1914 inv[ 4] = m[ 4] * (m[11] * m[14] - m[10] * m[15]) -
1915 m[ 8] * (m[ 7] * m[14] - m[ 6] * m[15]) -
1916 m[12] * (m[ 6] * m[11] - m[ 7] * m[10]);
1918 inv[ 5] = m[ 0] * (m[10] * m[15] - m[11] * m[14]) -
1919 m[ 8] * (m[ 2] * m[15] - m[ 3] * m[14]) -
1920 m[12] * (m[ 3] * m[10] - m[ 2] * m[11]);
1922 inv[ 6] = m[ 0] * (m[ 7] * m[14] - m[ 6] * m[15]) -
1923 m[ 4] * (m[ 3] * m[14] - m[ 2] * m[15]) -
1924 m[12] * (m[ 2] * m[ 7] - m[ 3] * m[ 6]);
1926 inv[ 7] = m[ 0] * (m[ 6] * m[11] - m[ 7] * m[10]) -
1927 m[ 4] * (m[ 2] * m[11] - m[ 3] * m[10]) -
1928 m[ 8] * (m[ 3] * m[ 6] - m[ 2] * m[ 7]);
1930 inv[ 8] = m[ 4] * (m[ 9] * m[15] - m[11] * m[13]) -
1931 m[ 8] * (m[ 5] * m[15] - m[ 7] * m[13]) -
1932 m[12] * (m[ 7] * m[ 9] - m[ 5] * m[11]);
1934 inv[ 9] = m[ 0] * (m[11] * m[13] - m[ 9] * m[15]) -
1935 m[ 8] * (m[ 3] * m[13] - m[ 1] * m[15]) -
1936 m[12] * (m[ 1] * m[11] - m[ 3] * m[ 9]);
1938 inv[10] = m[ 0] * (m[ 5] * m[15] - m[ 7] * m[13]) -
1939 m[ 4] * (m[ 1] * m[15] - m[ 3] * m[13]) -
1940 m[12] * (m[ 3] * m[ 5] - m[ 1] * m[ 7]);
1942 inv[11] = m[ 0] * (m[ 7] * m[ 9] - m[ 5] * m[11]) -
1943 m[ 4] * (m[ 3] * m[ 9] - m[ 1] * m[11]) -
1944 m[ 8] * (m[ 1] * m[ 7] - m[ 3] * m[ 5]);
1946 inv[12] = m[ 4] * (m[10] * m[13] - m[ 9] * m[14]) -
1947 m[ 8] * (m[ 6] * m[13] - m[ 5] * m[14]) -
1948 m[12] * (m[ 5] * m[10] - m[ 6] * m[ 9]);
1950 inv[13] = m[ 0] * (m[ 9] * m[14] - m[10] * m[13]) -
1951 m[ 8] * (m[ 1] * m[14] - m[ 2] * m[13]) -
1952 m[12] * (m[ 2] * m[ 9] - m[ 1] * m[10]);
1954 inv[14] = m[ 0] * (m[ 6] * m[13] - m[ 5] * m[14]) -
1955 m[ 4] * (m[ 2] * m[13] - m[ 1] * m[14]) -
1956 m[12] * (m[ 1] * m[ 6] - m[ 2] * m[ 5]);
1958 inv[15] = m[ 0] * (m[ 5] * m[10] - m[ 6] * m[ 9]) -
1959 m[ 4] * (m[ 1] * m[10] - m[ 2] * m[ 9]) -
1960 m[ 8] * (m[ 2] * m[ 5] - m[ 1] * m[ 6]);
1962 T det = m[0] * inv[ 0] +
1967 if (det == T (0.0)) return;
1969 det = T (1.0) / det;
1971 for (int i = 0; i < 16; ++i)
1975 // =======================================================================
1976 // function : GenerateCornerRays
1977 // purpose : Generates primary rays for corners of screen quad
1978 // =======================================================================
1979 void GenerateCornerRays (const GLdouble theInvModelProj[16],
1980 float theOrigins[16],
1981 float theDirects[16])
1983 int aOriginIndex = 0;
1984 int aDirectIndex = 0;
1986 for (int y = -1; y <= 1; y += 2)
1988 for (int x = -1; x <= 1; x += 2)
1990 OpenGl_RTVec4f aOrigin (float(x),
1995 aOrigin = MatVecMult (theInvModelProj, aOrigin);
1997 OpenGl_RTVec4f aDirect (float(x),
2002 aDirect = MatVecMult (theInvModelProj, aDirect) - aOrigin;
2004 GLdouble aInvLen = 1.f / sqrt (aDirect.x() * aDirect.x() +
2005 aDirect.y() * aDirect.y() +
2006 aDirect.z() * aDirect.z());
2008 theOrigins [aOriginIndex++] = static_cast<GLfloat> (aOrigin.x());
2009 theOrigins [aOriginIndex++] = static_cast<GLfloat> (aOrigin.y());
2010 theOrigins [aOriginIndex++] = static_cast<GLfloat> (aOrigin.z());
2011 theOrigins [aOriginIndex++] = 1.f;
2013 theDirects [aDirectIndex++] = static_cast<GLfloat> (aDirect.x() * aInvLen);
2014 theDirects [aDirectIndex++] = static_cast<GLfloat> (aDirect.y() * aInvLen);
2015 theDirects [aDirectIndex++] = static_cast<GLfloat> (aDirect.z() * aInvLen);
2016 theDirects [aDirectIndex++] = 0.f;
2021 // =======================================================================
2022 // function : Raytrace
2023 // purpose : Redraws the window using OpenCL ray tracing
2024 // =======================================================================
2025 Standard_Boolean OpenGl_Workspace::Raytrace (const Graphic3d_CView& theCView,
2028 const Tint theToSwap)
2031 return Standard_False;
2033 if (!ResizeRaytraceOutputBuffer (theSizeX, theSizeY))
2034 return Standard_False;
2036 if (!UpdateRaytraceEnvironmentMap())
2037 return Standard_False;
2039 if (!UpdateRaytraceGeometry (Standard_True))
2040 return Standard_False;
2042 // Get model-view and projection matrices
2043 TColStd_Array2OfReal theOrientation (0, 3, 0, 3);
2044 TColStd_Array2OfReal theViewMapping (0, 3, 0, 3);
2046 myView->GetMatrices (theOrientation, theViewMapping, Standard_True);
2048 GLdouble aOrientationMatrix[16];
2049 GLdouble aViewMappingMatrix[16];
2050 GLdouble aOrientationInvers[16];
2052 for (int j = 0; j < 4; ++j)
2053 for (int i = 0; i < 4; ++i)
2055 aOrientationMatrix [4 * j + i] = theOrientation (i, j);
2056 aViewMappingMatrix [4 * j + i] = theViewMapping (i, j);
2059 ComputeInverseMatrix (aOrientationMatrix, aOrientationInvers);
2061 if (!UpdateRaytraceLightSources (aOrientationInvers))
2062 return Standard_False;
2064 // Generate primary rays for corners of the screen quad
2065 glMatrixMode (GL_MODELVIEW);
2067 glLoadMatrixd (aViewMappingMatrix);
2068 glMultMatrixd (aOrientationMatrix);
2070 GLdouble aModelProject[16];
2071 GLdouble aInvModelProj[16];
2073 glGetDoublev (GL_MODELVIEW_MATRIX, aModelProject);
2075 ComputeInverseMatrix (aModelProject, aInvModelProj);
2077 GLfloat aOrigins[16];
2078 GLfloat aDirects[16];
2080 GenerateCornerRays (aInvModelProj,
2084 // Compute ray-traced image using OpenCL kernel
2085 cl_mem anImages[] = { myRaytraceOutputImage, myRaytraceOutputImageSmooth };
2086 cl_int anError = clEnqueueAcquireGLObjects (myRaytraceQueue,
2089 clFinish (myRaytraceQueue);
2091 if (myIsRaytraceDataValid)
2093 RunRaytraceOpenCLKernels (theCView,
2100 anError |= clEnqueueReleaseGLObjects (myRaytraceQueue,
2103 clFinish (myRaytraceQueue);
2106 glPushAttrib (GL_ENABLE_BIT |
2108 GL_COLOR_BUFFER_BIT |
2109 GL_DEPTH_BUFFER_BIT);
2111 glDisable (GL_DEPTH_TEST);
2113 if (NamedStatus & OPENGL_NS_WHITEBACK)
2115 glClearColor (1.0f, 1.0f, 1.0f, 1.0f);
2119 glClearColor (myBgColor.rgb[0],
2125 glClear (GL_COLOR_BUFFER_BIT);
2127 Handle(OpenGl_Workspace) aWorkspace (this);
2128 myView->DrawBackground (aWorkspace);
2130 // Draw dummy quad to show result image
2131 glEnable (GL_COLOR_MATERIAL);
2132 glEnable (GL_BLEND);
2134 glDisable (GL_DEPTH_TEST);
2136 glBlendFunc (GL_ONE, GL_SRC_ALPHA);
2138 glEnable (GL_TEXTURE_RECTANGLE);
2140 glMatrixMode (GL_PROJECTION);
2143 glMatrixMode (GL_MODELVIEW);
2146 glColor3f (1.0f, 1.0f, 1.0f);
2148 glBindTexture (GL_TEXTURE_RECTANGLE, myRaytraceOutputTexture[theCView.IsAntialiasingEnabled ? 1 : 0]);
2150 if (myIsRaytraceDataValid)
2154 glTexCoord2i ( 0, 0); glVertex2f (-1.f, -1.f);
2155 glTexCoord2i ( 0, theSizeY); glVertex2f (-1.f, 1.f);
2156 glTexCoord2i (theSizeX, theSizeY); glVertex2f ( 1.f, 1.f);
2157 glTexCoord2i (theSizeX, 0); glVertex2f ( 1.f, -1.f);
2167 GetGlContext()->SwapBuffers();
2168 myBackBufferRestored = Standard_False;
2173 return Standard_True;