0024320: TKOpenGl, Ray Tracing - OpenGL resources created for OpenCL interconnection...
[occt.git] / src / OpenGl / OpenGl_Workspace.hxx
1 // Created on: 2011-09-20
2 // Created by: Sergey ZERCHANINOV
3 // Copyright (c) 2011-2013 OPEN CASCADE SAS
4 //
5 // This file is part of Open CASCADE Technology software library.
6 //
7 // This library is free software; you can redistribute it and / or modify it
8 // under the terms of the GNU Lesser General Public version 2.1 as published
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.
12 //
13 // Alternatively, this file may be used under the terms of Open CASCADE
14 // commercial license or contractual agreement.
15
16 #ifndef _OpenGl_Workspace_Header
17 #define _OpenGl_Workspace_Header
18
19 #ifdef HAVE_OPENCL
20   #include <map>
21   #include <set>
22
23   #include <OpenGl_Cl.hxx>
24 #endif
25
26 #include <Handle_OpenGl_Workspace.hxx>
27 #include <OpenGl_Window.hxx>
28
29 #include <TColStd_Array2OfReal.hxx>
30 #include <Quantity_Color.hxx>
31 #include <Graphic3d_CView.hxx>
32 #include <Graphic3d_TypeOfComposition.hxx>
33 #include <Graphic3d_TypeOfTexture.hxx>
34 #include <Graphic3d_PtrFrameBuffer.hxx>
35 #include <Graphic3d_BufferType.hxx>
36 #include <Handle_Graphic3d_TextureParams.hxx>
37
38 #include <Aspect_CLayer2d.hxx>
39 #include <Aspect_Handle.hxx>
40 #include <Aspect_PrintAlgo.hxx>
41
42 #include <InterfaceGraphic_Graphic3d.hxx>
43 #include <InterfaceGraphic_Visual3d.hxx>
44
45 #include <NCollection_Sequence.hxx>
46
47 #include <OpenGl_tsm.hxx>
48
49 #include <OpenGl_AspectFace.hxx>
50 #include <OpenGl_Display.hxx>
51 #include <OpenGl_Matrix.hxx>
52 #include <OpenGl_NamedStatus.hxx>
53 #include <OpenGl_PrinterContext.hxx>
54 #ifdef HAVE_OPENCL
55   #include <OpenGl_SceneGeometry.hxx>
56 #endif
57 #include <OpenGl_TextParam.hxx>
58 #include <OpenGl_RenderFilter.hxx>
59 #include <OpenGl_Vec.hxx>
60
61 #include <Handle_OpenGl_View.hxx>
62 #include <Handle_OpenGl_Texture.hxx>
63
64 class OpenGl_AspectLine;
65 class OpenGl_AspectMarker;
66 class OpenGl_AspectText;
67 class OpenGl_FrameBuffer;
68 class OpenGl_Structure;
69 class OpenGl_Element;
70 class Image_PixMap;
71
72 //! OpenGL material definition
73 struct OpenGl_Material
74 {
75
76   OpenGl_Vec4 Ambient;  //!< ambient reflection coefficient
77   OpenGl_Vec4 Diffuse;  //!< diffuse reflection coefficient
78   OpenGl_Vec4 Specular; //!< glossy  reflection coefficient
79   OpenGl_Vec4 Emission; //!< material emission
80   OpenGl_Vec4 Params;   //!< extra packed parameters
81
82   Standard_ShortReal  Shine()              const { return Params.x(); }
83   Standard_ShortReal& ChangeShine()              { return Params.x(); }
84
85   Standard_ShortReal  Transparency()       const { return Params.y(); }
86   Standard_ShortReal& ChangeTransparency()       { return Params.y(); }
87
88   //! Initialize material
89   void Init (const OPENGL_SURF_PROP& theProps);
90
91   //! Returns packed (serialized) representation of material properties
92   const OpenGl_Vec4* Packed() const { return reinterpret_cast<const OpenGl_Vec4*> (this); }
93   static Standard_Integer NbOfVec4() { return 5; }
94
95 };
96
97 //! Represents window with GL context.
98 //! Provides methods to render primitives and maintain GL state.
99 class OpenGl_Workspace : public OpenGl_Window
100 {
101 public:
102
103   //! Main constructor - prepare GL context for specified window.
104   OpenGl_Workspace (const Handle(OpenGl_Display)& theDisplay,
105                     const CALL_DEF_WINDOW&        theCWindow,
106                     Aspect_RenderingContext       theGContext,
107                     const Handle(OpenGl_Caps)&    theCaps,
108                     const Handle(OpenGl_Context)& theShareCtx);
109
110   //! Destructor
111   virtual ~OpenGl_Workspace();
112
113   void SetActiveView (const Handle(OpenGl_View)& theView) { myView = theView; }
114   const Handle(OpenGl_View)& ActiveView () const { return myView; }
115
116   //! Redraw the window.
117   void Redraw (const Graphic3d_CView& theCView,
118                const Aspect_CLayer2d& theCUnderLayer,
119                const Aspect_CLayer2d& theCOverLayer);
120
121   //! Deprecated. Simply calls Redraw().
122   void Update (const Graphic3d_CView& theCView,
123                const Aspect_CLayer2d& theCUnderLayer,
124                const Aspect_CLayer2d& theCOverLayer)
125   {
126     Redraw (theCView, theCUnderLayer, theCOverLayer);
127   }
128
129   //! Special method to perform printing.
130   //! System-specific and currently only Win platform implemented.
131   Standard_Boolean Print (const Handle(OpenGl_PrinterContext)& thePrintContext,
132                           const Graphic3d_CView& theCView,
133                           const Aspect_CLayer2d& theCUnderLayer,
134                           const Aspect_CLayer2d& theCOverLayer,
135                           const Aspect_Handle    theHPrintDC,
136                           const Standard_Boolean theToShowBackground,
137                           const Standard_CString theFileName,
138                           const Aspect_PrintAlgo thePrintAlgorithm,
139                           const Standard_Real    theScaleFactor);
140
141   const Handle(OpenGl_PrinterContext)& PrinterContext() const
142   {
143     return myPrintContext;
144   }
145
146   void DisplayCallback (const Graphic3d_CView& theCView, int theReason);
147
148   Standard_Boolean SetImmediateModeDrawToFront (const Standard_Boolean theDrawToFrontBuffer);
149   Standard_Boolean BeginAddMode();
150   void EndAddMode();
151   void ClearImmediatMode (const Graphic3d_CView& theCView,
152                           const Standard_Boolean theToFlush);
153   void RedrawImmediatMode();
154   Standard_Boolean BeginImmediatMode (const Graphic3d_CView& theCView,
155                                       const Standard_Boolean theUseDepthTest,
156                                       const Standard_Boolean theRetainMode);
157   void EndImmediatMode();
158   void DrawStructure (const OpenGl_Structure* theStructure);
159
160   Graphic3d_PtrFrameBuffer FBOCreate (const Standard_Integer theWidth, const Standard_Integer theHeight);
161   void FBORelease (Graphic3d_PtrFrameBuffer theFBOPtr);
162   Standard_Boolean BufferDump (OpenGl_FrameBuffer*         theFBOPtr,
163                                Image_PixMap&               theImage,
164                                const Graphic3d_BufferType& theBufferType);
165
166   void UseTransparency (const Standard_Boolean theFlag);
167   Standard_Boolean& UseZBuffer()   { return myUseZBuffer; }
168   Standard_Boolean& UseDepthTest() { return myUseDepthTest; }
169   Standard_Boolean& UseGLLight()   { return myUseGLLight; }
170
171   //// RELATED TO STATUS ////
172
173   Standard_Integer   NamedStatus;
174
175   const TEL_COLOUR* HighlightColor;
176
177   const OpenGl_Matrix* SetViewMatrix (const OpenGl_Matrix* );
178   const OpenGl_Matrix* SetStructureMatrix (const OpenGl_Matrix*, bool aRevert = false);
179
180   //! Updates current model-view matrix
181   //! replacing it with StructureMatrixT*ViewMatrix from the workspace.
182   const void UpdateModelViewMatrix();
183
184   const OpenGl_AspectLine*   SetAspectLine   (const OpenGl_AspectLine*   theAspect);
185   const OpenGl_AspectFace*   SetAspectFace   (const OpenGl_AspectFace*   theAspect);
186   const OpenGl_AspectMarker* SetAspectMarker (const OpenGl_AspectMarker* theAspect);
187   const OpenGl_AspectText*   SetAspectText   (const OpenGl_AspectText*   theAspect);
188
189   void SetTextParam (const OpenGl_TextParam* theParam) { TextParam_set = theParam; }
190
191   //// THESE METHODS ARE EXPORTED AS THEY PROVIDE STATE INFO TO USERDRAW
192   Standard_EXPORT const OpenGl_AspectLine*   AspectLine   (const Standard_Boolean theWithApply);
193   Standard_EXPORT const OpenGl_AspectFace*   AspectFace   (const Standard_Boolean theWithApply);
194   Standard_EXPORT const OpenGl_AspectMarker* AspectMarker (const Standard_Boolean theWithApply);
195   Standard_EXPORT const OpenGl_AspectText*   AspectText   (const Standard_Boolean theWithApply);
196   inline const OpenGl_TextParam* AspectTextParams() const
197   {
198     return TextParam_applied;
199   }
200
201   //! Clear the applied aspect state.
202   void ResetAppliedAspect();
203
204   Standard_EXPORT Handle(OpenGl_Texture) DisableTexture();
205   Standard_EXPORT Handle(OpenGl_Texture) EnableTexture (const Handle(OpenGl_Texture)&          theTexture,
206                                                         const Handle(Graphic3d_TextureParams)& theParams = NULL);
207
208   //! Set filter for restricting rendering of particular elements.
209   //! Filter can be applied for rendering passes used by recursive
210   //! rendering algorithms for rendering elements of groups.
211   //! @param theFilter [in] the filter instance.
212   inline void SetRenderFilter (const Handle(OpenGl_RenderFilter)& theFilter)
213   {
214     myRenderFilter = theFilter; 
215   }
216
217   //! Get rendering filter.
218   //! @return filter instance.
219   inline const Handle(OpenGl_RenderFilter)& GetRenderFilter() const 
220   { 
221     return myRenderFilter; 
222   }
223
224   //! @return applied view matrix.
225   inline const OpenGl_Matrix* ViewMatrix() const { return ViewMatrix_applied; }
226
227   //! @return applied model structure matrix.
228   inline const OpenGl_Matrix* ModelMatrix() const { return StructureMatrix_applied; }
229
230 protected:
231
232   void CopyBuffers (const Standard_Boolean theFrontToBack);
233
234   virtual Standard_Boolean Activate();
235
236   // TEMPORARY!!!
237   void Redraw1 (const Graphic3d_CView& theCView,
238                 const Aspect_CLayer2d& theCUnderLayer,
239                 const Aspect_CLayer2d& theCOverLayer,
240                 const int theToSwap);
241
242   void updateMaterial (const int theFlag);
243
244   void setTextureParams (Handle(OpenGl_Texture)&                theTexture,
245                          const Handle(Graphic3d_TextureParams)& theParams);
246
247 #ifdef HAVE_OPENCL
248
249 public:
250
251   //! Returns information about OpenCL device used for computations.
252   Standard_Boolean GetOpenClDeviceInfo (
253     NCollection_DataMap<TCollection_AsciiString, TCollection_AsciiString>& theInfo) const;
254
255 protected:
256
257   //! Describes result of OpenCL initializing.
258   enum OpenClInitStatus
259   {
260     OpenGl_CLIS_NONE,
261     OpenGl_CLIS_INIT,
262     OpenGl_CLIS_FAIL
263   };
264
265 protected: //! @name methods related to ray-tracing
266
267   //! Updates 3D scene geometry for ray-tracing.
268   Standard_Boolean UpdateRaytraceGeometry (Standard_Boolean theCheck);
269
270   //! Checks to see if the structure is modified.
271   Standard_Boolean CheckRaytraceStructure (const OpenGl_Structure* theStructure);
272
273   //! Updates 3D scene light sources for ray-tracing.
274   Standard_Boolean UpdateRaytraceLightSources (const GLdouble theInvModelView[16]);
275
276   //! Updates environment map for ray-tracing.
277   Standard_Boolean UpdateRaytraceEnvironmentMap();
278
279   //! Adds OpenGL structure to ray-traced scene geometry.
280   Standard_Boolean AddRaytraceStructure (const OpenGl_Structure* theStruct,
281                        const float* theTrans, std::set<const OpenGl_Structure*>& theElements);
282
283   //! Adds OpenGL primitive array to ray-traced scene geometry.
284   Standard_Boolean AddRaytracePrimitiveArray (
285                        const CALL_DEF_PARRAY* theArray, int theMatID, const float* theTrans);
286
287   //! Adds vertex indices from OpenGL primitive array to ray-traced scene geometry.
288   Standard_Boolean AddRaytraceVertexIndices (const CALL_DEF_PARRAY* theArray,
289    int theFirstVert, int theVertOffset, int theVertNum, int theMatID);
290
291   //! Adds OpenGL triangle array to ray-traced scene geometry.
292   Standard_Boolean AddRaytraceTriangleArray (const CALL_DEF_PARRAY* theArray,
293                               int theFirstVert, int theVertOffset, int theVertNum, int theMatID);
294
295   //! Adds OpenGL triangle fan array to ray-traced scene geometry.
296   Standard_Boolean AddRaytraceTriangleFanArray (const CALL_DEF_PARRAY* theArray,
297                               int theFirstVert, int theVertOffset, int theVertNum, int theMatID);
298
299   //! Adds OpenGL triangle fan array to ray-traced scene geometry.
300   Standard_Boolean AddRaytraceTriangleStripArray (const CALL_DEF_PARRAY* theArray,
301                               int theFirstVert, int theVertOffset, int theVertNum, int theMatID);
302
303   //! Adds OpenGL quadrangle array to ray-traced scene geometry.
304   Standard_Boolean AddRaytraceQuadrangleArray (const CALL_DEF_PARRAY* theArray,
305                               int theFirstVert, int theVertOffset, int theVertNum, int theMatID);
306
307   //! Adds OpenGL quadrangle strip array to ray-traced scene geometry.
308   Standard_Boolean AddRaytraceQuadrangleStripArray (const CALL_DEF_PARRAY* theArray,
309                               int theFirstVert, int theVertOffset, int theVertNum, int theMatID);
310
311   //! Adds OpenGL polygon array to ray-traced scene geometry.
312   Standard_Boolean AddRaytracePolygonArray (const CALL_DEF_PARRAY* theArray,
313                               int theFirstVert, int theVertOffset, int theVertNum, int theMatID);
314
315   //! Initializes OpenCL resources.
316   Standard_Boolean InitOpenCL();
317   
318   //! Releases OpenCL resources.
319   void ReleaseOpenCL();
320
321   //! Resizes OpenCL output image.
322   Standard_Boolean ResizeRaytraceOutputBuffer (const cl_int theSizeX, const cl_int theSizeY);
323
324   //! Writes scene geometry to OpenCl device.
325   Standard_Boolean WriteRaytraceSceneToDevice();
326
327   //! Runs OpenCL ray-tracing kernels.
328   Standard_Boolean RunRaytraceOpenCLKernels (const Graphic3d_CView& theCView,
329                                              const GLfloat theOrigins[16],
330                                              const GLfloat theDirects[16],
331                                              const int theSizeX,
332                                              const int theSizeY);
333
334   //! Redraws the window using OpenCL ray tracing.
335   Standard_Boolean Raytrace (const Graphic3d_CView& theCView,
336               const int theSizeX, const int theSizeY, const Tint theToSwap);
337
338 protected: //! @name fields related to ray-tracing
339
340   //! Result of OpenCL initialization.
341   OpenClInitStatus myComputeInitStatus;
342   //! Is ATI/AMD OpenCL platform used?
343   Standard_Boolean myIsAmdComputePlatform;
344
345   //! Is geometry data valid?
346   Standard_Boolean myIsRaytraceDataValid;
347   //! Is geometry data musty be updated?
348   Standard_Boolean myToUpdateRaytraceData;
349   //! 3D scene geometry data for ray-tracing.
350   OpenGl_RaytraceScene myRaytraceSceneData;
351
352   //! Radius of bounding sphere of the scene.
353   float myRaytraceSceneRadius;
354   //! Scene epsilon to prevent self-intersections.
355   float myRaytraceSceneEpsilon;
356
357   //! Binned SAH-based BVH builder.
358   OpenGl_BinnedBVHBuilder myBVHBuilder;
359
360   //! OpenCL context.
361   cl_context myComputeContext;
362   //! OpenCL command queue.
363   cl_command_queue myRaytraceQueue;
364   //! OpenCL computing program.
365   cl_program myRaytraceProgram;
366   //! OpenCL ray-tracing render kernel.
367   cl_kernel myRaytraceRenderKernel;
368   //! OpenCL adaptive anti-aliasing kernel.
369   cl_kernel myRaytraceSmoothKernel;
370
371   //! OpenCL image to store environment map.
372   cl_mem myRaytraceEnvironment;
373   //! OpenCL image to store rendering result.
374   cl_mem myRaytraceOutputImage;
375   //! OpenCL image to store anti-aliasing result.
376   cl_mem myRaytraceOutputImageAA;
377
378   //! OpenGL texture to store rendering result.
379   Handle(OpenGl_Texture) myRaytraceOutputTexture;
380   //! OpenGL texture to store anti-aliasing result.
381   Handle(OpenGl_Texture) myRaytraceOutputTextureAA;
382
383   //! OpenCL buffer of vertex normals.
384   cl_mem myRaytraceNormalBuffer;
385   //! OpenCL buffer of vertex coordinates.
386   cl_mem myRaytraceVertexBuffer;
387   //! OpenCL buffer of indices of triangle vertices.
388   cl_mem myRaytraceTriangleBuffer;
389
390   //! OpenCL buffer of minimum points of BVH nodes.
391   cl_mem myRaytraceNodeMinPointBuffer;
392   //! OpenCL buffer of maximum points of BVH nodes.
393   cl_mem myRaytraceNodeMaxPointBuffer;
394   //! OpenCL buffer of data records of BVH nodes.
395   cl_mem myRaytraceNodeDataRcrdBuffer;
396
397   //! OpenCL buffer of material properties.
398   cl_mem myRaytraceMaterialBuffer;
399   
400   //! OpenCL buffer of light source properties.
401   cl_mem myRaytraceLightSourceBuffer;
402
403   //! State of OpenGL view.
404   Standard_Size myViewModificationStatus;
405
406   //! State of OpenGL layer list.
407   Standard_Size myLayersModificationStatus;
408
409   //! State of OpenGL elements reflected to ray-tracing.
410   std::map<const OpenGl_Structure*, Standard_Size> myStructureStates;
411
412 #endif // HAVE_OPENCL
413
414 protected: //! @name protected fields
415
416   Handle(OpenGl_PrinterContext) myPrintContext;
417   Handle(OpenGl_View)    myView;            // WSViews - now just one view is supported
418   Standard_Boolean       myIsTransientOpen; // transientOpen
419   Standard_Boolean       myRetainMode;
420   Standard_Boolean       myTransientDrawToFront; //!< optimization flag for immediate mode (to render directly to the front buffer)
421
422   NCollection_Sequence<const OpenGl_Structure*> myTransientList;
423
424   Standard_Boolean       myUseTransparency;
425   Standard_Boolean       myUseZBuffer;
426   Standard_Boolean       myUseDepthTest;
427   Standard_Boolean       myUseGLLight;
428   Standard_Boolean       myBackBufferRestored;
429
430 protected: //! @name fields related to status
431
432   Handle(OpenGl_RenderFilter) myRenderFilter;
433   Handle(OpenGl_Texture) myTextureBound;    //!< currently bound texture (managed by OpenGl_AspectFace and OpenGl_View environment texture)
434   const OpenGl_AspectLine *AspectLine_set, *AspectLine_applied;
435   const OpenGl_AspectFace *AspectFace_set, *AspectFace_applied;
436   const OpenGl_AspectMarker *AspectMarker_set, *AspectMarker_applied;
437   const OpenGl_AspectText *AspectText_set, *AspectText_applied;
438
439   const OpenGl_TextParam *TextParam_set, *TextParam_applied;
440
441   const OpenGl_Matrix* ViewMatrix_applied;
442   const OpenGl_Matrix* StructureMatrix_applied;
443
444   OpenGl_Material myMatFront;    //!< current front material state (cached to reduce GL context updates)
445   OpenGl_Material myMatBack;     //!< current back  material state
446   OpenGl_Material myMatTmp;      //!< temporary variable
447   TelCullMode     myCullingMode; //!< back face culling mode, applied from face aspect
448
449   //! Model matrix with applied structure transformations
450   OpenGl_Matrix myModelViewMatrix;
451
452   const TEL_POFFSET_PARAM* PolygonOffset_applied;
453
454   OpenGl_AspectFace myAspectFaceHl; // Hiddenline aspect
455
456 public: //! @name type definition
457
458   DEFINE_STANDARD_RTTI(OpenGl_Workspace)
459   DEFINE_STANDARD_ALLOC
460
461 };
462
463 #endif // _OpenGl_Workspace_Header