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