0033056: Visualization - add front face culling option
[occt.git] / src / OpenGl / OpenGl_Context.hxx
1 // Created on: 2012-01-26
2 // Created by: Kirill GAVRILOV
3 // Copyright (c) 2012-2014 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_Context_HeaderFile
17 #define OpenGl_Context_HeaderFile
18
19 #include <Aspect_Drawable.hxx>
20 #include <Aspect_Display.hxx>
21 #include <Aspect_GraphicsLibrary.hxx>
22 #include <Aspect_RenderingContext.hxx>
23 #include <Graphic3d_DiagnosticInfo.hxx>
24 #include <Message.hxx>
25 #include <OpenGl_Caps.hxx>
26 #include <OpenGl_LineAttributes.hxx>
27 #include <OpenGl_Material.hxx>
28 #include <OpenGl_MatrixState.hxx>
29 #include <OpenGl_Vec.hxx>
30 #include <OpenGl_Resource.hxx>
31 #include <OpenGl_TextureSet.hxx>
32 #include <Standard_Transient.hxx>
33 #include <TColStd_IndexedDataMapOfStringString.hxx>
34 #include <TColStd_PackedMapOfInteger.hxx>
35 #include <OpenGl_Clipping.hxx>
36
37 #include <NCollection_Shared.hxx>
38
39 #include <memory>
40
41 //! Forward declarations
42 #if defined(__APPLE__)
43   #import <TargetConditionals.h>
44   #if defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE
45     #ifdef __OBJC__
46       @class EAGLContext;
47     #else
48       struct EAGLContext;
49     #endif
50   #else
51     #ifdef __OBJC__
52       @class NSOpenGLContext;
53     #else
54       struct NSOpenGLContext;
55     #endif
56   #endif
57 #endif
58
59 struct OpenGl_GlFunctions;
60 struct OpenGl_ArbTBO;
61 struct OpenGl_ArbIns;
62 struct OpenGl_ArbDbg;
63 struct OpenGl_ArbFBO;
64 struct OpenGl_ArbFBOBlit;
65 struct OpenGl_ArbSamplerObject;
66 struct OpenGl_ArbTexBindless;
67 struct OpenGl_ExtGS;
68
69 struct OpenGl_GlCore11Fwd;
70 struct OpenGl_GlCore11;
71 struct OpenGl_GlCore12;
72 struct OpenGl_GlCore13;
73 struct OpenGl_GlCore14;
74 struct OpenGl_GlCore15;
75 struct OpenGl_GlCore20;
76 struct OpenGl_GlCore21;
77 struct OpenGl_GlCore30;
78 struct OpenGl_GlCore31;
79 struct OpenGl_GlCore32;
80 struct OpenGl_GlCore33;
81 struct OpenGl_GlCore40;
82 struct OpenGl_GlCore41;
83 struct OpenGl_GlCore42;
84 struct OpenGl_GlCore43;
85 struct OpenGl_GlCore44;
86 struct OpenGl_GlCore45;
87 struct OpenGl_GlCore46;
88
89 class Graphic3d_Camera;
90 class Graphic3d_PresentationAttributes;
91 class OpenGl_Aspects;
92 class OpenGl_FrameBuffer;
93 class OpenGl_ShaderProgram;
94 class OpenGl_ShaderManager;
95 class OpenGl_FrameStats;
96
97 enum OpenGl_FeatureFlag
98 {
99   OpenGl_FeatureNotAvailable = 0, //!< Feature is not supported by OpenGl implementation.
100   OpenGl_FeatureInExtensions = 1, //!< Feature is supported as extension.
101   OpenGl_FeatureInCore       = 2  //!< Feature is supported as part of core profile.
102 };
103
104 DEFINE_STANDARD_HANDLE(OpenGl_Context, Standard_Transient)
105
106 //! This class generalize access to the GL context and available extensions.
107 //!
108 //! Functions related to specific OpenGL version or extension are grouped into structures which can be accessed as fields of this class.
109 //! The most simple way to check that required functionality is available - is NULL check for the group:
110 //! @code
111 //!   if (myContext->core20 != NULL)
112 //!   {
113 //!     myGlProgram = myContext->core20->glCreateProgram();
114 //!     .. do more stuff ..
115 //!   }
116 //!   else
117 //!   {
118 //!     .. compatibility with outdated configurations ..
119 //!   }
120 //! @endcode
121 //!
122 //! Current implementation provide access to OpenGL core functionality up to 4.6 version (core12, core13, core14, etc.)
123 //! as well as several extensions (arbTBO, arbFBO, etc.).
124 //!
125 //! OpenGL context might be initialized in Core Profile. In this case deprecated functionality become unavailable.
126 //! To select which core** function set should be used in specific case:
127 //!  - Determine the minimal OpenGL version required for implemented functionality and use it to access all functions.
128 //!    For example, if algorithm requires OpenGL 2.1+, it is better to write core20fwd->glEnable() rather than core11fwd->glEnable() for uniformity.
129 //!  - Validate minimal requirements at initialization/creation time and omit checks within code where algorithm should be already initialized.
130 //!    Properly escape code incompatible with Core Profile. The simplest way to check Core Profile is "if (core11ffp == NULL)".
131 //!
132 //! Simplified extensions classification:
133 //!  - prefixed with NV, AMD, ATI are vendor-specific (however may be provided by other vendors in some cases);
134 //!  - prefixed with EXT are accepted by 2+ vendors;
135 //!  - prefixed with ARB are accepted by Architecture Review Board and are candidates
136 //!    for inclusion into GL core functionality.
137 //! Some functionality can be represented in several extensions simultaneously.
138 //! In this case developer should be careful because different specification may differ
139 //! in aspects (like enumeration values and error-handling).
140 //!
141 //! Notice that some systems provide mechanisms to simultaneously incorporate with GL contexts with different capabilities.
142 //! For this reason OpenGl_Context should be initialized and used for each GL context independently.
143 //!
144 //! Matrices of OpenGl transformations:
145 //! model -> world -> view -> projection
146 //! These matrices might be changed for local transformation, transform persistent using direct access to
147 //! current matrix of ModelWorldState, WorldViewState and ProjectionState
148 //! After, these matrices should be applied using ApplyModelWorldMatrix, ApplyWorldViewMatrix,
149 //! ApplyModelViewMatrix or ApplyProjectionMatrix.
150 class OpenGl_Context : public Standard_Transient
151 {
152   DEFINE_STANDARD_RTTIEXT(OpenGl_Context, Standard_Transient)
153   friend class OpenGl_Window;
154   friend struct OpenGl_GlFunctions;
155 public:
156
157   typedef NCollection_Shared< NCollection_DataMap<TCollection_AsciiString, Handle(OpenGl_Resource)> > OpenGl_ResourcesMap;
158
159   //! Function for getting power of to number larger or equal to input number.
160   //! @param theNumber    number to 'power of two'
161   //! @param theThreshold upper threshold
162   //! @return power of two number
163   inline static Standard_Integer GetPowerOfTwo (const Standard_Integer theNumber,
164                                                 const Standard_Integer theThreshold)
165   {
166     for (Standard_Integer p2 = 2; p2 <= theThreshold; p2 <<= 1)
167     {
168       if (theNumber <= p2)
169       {
170         return p2;
171       }
172     }
173     return theThreshold;
174   }
175
176   //! Format GL constant as hex value 0xABCD.
177   Standard_EXPORT static TCollection_AsciiString FormatGlEnumHex (int theGlEnum);
178
179   //! Format pointer as hex value 0xABCD.
180   Standard_EXPORT static TCollection_AsciiString FormatPointer (const void* thePtr);
181
182   //! Format size value.
183   Standard_EXPORT static TCollection_AsciiString FormatSize (Standard_Size theSize);
184
185   //! Return text description of GL error.
186   Standard_EXPORT static TCollection_AsciiString FormatGlError (int theGlError);
187
188 public:
189
190   //! Empty constructor. You should call Init() to perform initialization with bound GL context.
191   Standard_EXPORT OpenGl_Context (const Handle(OpenGl_Caps)& theCaps = NULL);
192
193   //! Destructor.
194   Standard_EXPORT virtual ~OpenGl_Context();
195
196   //! Release all resources, including shared ones
197   Standard_EXPORT void forcedRelease();
198
199   //! Share GL context resources.
200   //! theShareCtx - handle to context to retrieve handles to shared resources.
201   Standard_EXPORT void Share (const Handle(OpenGl_Context)& theShareCtx);
202
203   //! Initialize class from currently bound OpenGL context. Method should be called only once.
204   //! @return false if no GL context is bound to the current thread
205   Standard_EXPORT Standard_Boolean Init (const Standard_Boolean theIsCoreProfile = Standard_False);
206
207   //! @return true if this context is valid (has been initialized)
208   inline Standard_Boolean IsValid() const
209   {
210     return myIsInitialized;
211   }
212
213   //! Initialize class from specified surface and rendering context. Method should be called only once.
214   //! The meaning of parameters is platform-specific.
215   //!
216   //! EGL:
217   //! @code
218   //!   Handle(Aspect_Window) theAspWin;
219   //!   EGLSurface theEglSurf = eglCreateWindowSurface (theEglDisp, anEglConfig, (EGLNativeWindowType )theAspWin->NativeHandle(), NULL);
220   //!   EGLDisplay theEglDisp = eglGetDisplay (EGL_DEFAULT_DISPLAY);
221   //!   EGLContext theEglCtx  = eglCreateContext ((EGLDisplay )theEglDisp, anEglConfig, EGL_NO_CONTEXT, anEglCtxAttribs);
222   //!   Handle(OpenGl_Context) aGlCtx = new OpenGl_Context();
223   //!   aGlCtx->Init ((Aspect_Drawable )theEglSurf, (Aspect_Display )theEglDisp,  (Aspect_RenderingContext )theEglCtx);
224   //! @endcode
225   //!
226   //! Windows (Win32):
227   //! @code
228   //!   Handle(WNT_Window) theAspWin;
229   //!   HWND  theWindow   = (HWND )theAspWin->NativeHandle();
230   //!   HDC   theDevCtx   = GetDC(theWindow);
231   //!   HGLRC theGContext = wglCreateContext (theDevCtx);
232   //!   Handle(OpenGl_Context) aGlCtx = new OpenGl_Context();
233   //!   aGlCtx->Init ((Aspect_Drawable )theWindow, (Aspect_Display )theDevCtx, (Aspect_RenderingContext )theGContext);
234   //! @endcode
235   //!
236   //! Linux (Xlib):
237   //! @code
238   //!   Handle(Xw_Window) theAspWin;
239   //!   Window     theXWindow = (Window )theAspWin->NativeHandle();
240   //!   Display*   theXDisp   = (Display* )theAspWin->DisplayConnection()->GetDisplayAspect();
241   //!   GLXContext theGlxCtx  = glXCreateContext (theXDisp, aVis.get(), NULL, GL_TRUE);
242   //!   Handle(OpenGl_Context) aGlCtx = new OpenGl_Context();
243   //!   aGlCtx->Init ((Aspect_Drawable )theXWindow, (Aspect_Display )theXDisp,  (Aspect_RenderingContext )theGlxCtx);
244   //! @endcode
245   //!
246   //! @param theSurface [in] surface / window          (EGLSurface | HWND  | GLXDrawable/Window)
247   //! @param theDisplay [in] display or device context (EGLDisplay | HDC   | Display*)
248   //! @param theContext [in] rendering context         (EGLContext | HGLRC | GLXContext | EAGLContext* | NSOpenGLContext*)
249   //! @param theIsCoreProfile [in] flag indicating that passed GL rendering context has been created with Core Profile
250   //! @return false if OpenGL context can not be bound to specified surface
251   Standard_EXPORT Standard_Boolean Init (const Aspect_Drawable         theSurface,
252                                          const Aspect_Display          theDisplay,
253                                          const Aspect_RenderingContext theContext,
254                                          const Standard_Boolean        theIsCoreProfile = Standard_False);
255
256   //! Return window handle currently bound to this OpenGL context (EGLSurface | HWND | GLXDrawable).
257   Aspect_Drawable Window() const { return myWindow; }
258
259   //! Return display / window device context (EGLDisplay | HDC | Display*).
260   Aspect_Display GetDisplay() const { return myDisplay; }
261
262   //! Return rendering context (EGLContext | HGLRC | GLXContext | EAGLContext* | NSOpenGLContext*).
263   Aspect_RenderingContext RenderingContext() const { return myGContext; }
264
265 #if defined(__APPLE__) && !defined(HAVE_XLIB)
266   #if defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE
267
268   //! Initialize class from specified OpenGL ES context (EAGLContext). Method should be called only once.
269   Standard_Boolean Init (EAGLContext*           theGContext,
270                          const Standard_Boolean theIsCoreProfile = Standard_False)
271   {
272     return Init ((Aspect_Drawable )0, (Aspect_Display )0, (Aspect_RenderingContext )theGContext, theIsCoreProfile);
273   }
274   #else
275   //! Initialize class from specified OpenGL context (NSOpenGLContext). Method should be called only once.
276   Standard_Boolean Init (NSOpenGLContext*       theGContext,
277                          const Standard_Boolean theIsCoreProfile = Standard_False)
278   {
279     return Init ((Aspect_Drawable )0, (Aspect_Display )0, (Aspect_RenderingContext )theGContext, theIsCoreProfile);
280   }
281   #endif
282 #endif
283
284   //! Read OpenGL version information from active context.
285   Standard_EXPORT static void ReadGlVersion (Standard_Integer& theGlVerMajor,
286                                              Standard_Integer& theGlVerMinor);
287
288   //! Check if theExtName extension is supported by active GL context.
289   Standard_EXPORT Standard_Boolean CheckExtension (const char* theExtName) const;
290
291   //! Check if theExtName extension is in extensions string.
292   Standard_EXPORT static Standard_Boolean CheckExtension (const char* theExtString,
293                                                           const char* theExtName);
294
295   //! Auxiliary template to retrieve GL function pointer.
296   //! Pointer to function retrieved from library is statically casted
297   //! to requested type - there no way to check real signature of exported function.
298   //! The context should be bound before call.
299   //! @param theLastFailFuncName [out] set to theFuncName in case of failure, unmodified on success
300   //! @param theFuncName [in] function name to find
301   //! @param theFuncPtr [out] retrieved function pointer
302   //! @return TRUE on success
303   template <typename FuncType_t>
304   Standard_Boolean FindProcVerbose (const char*& theLastFailFuncName,
305                                     const char* theFuncName,
306                                     FuncType_t& theFuncPtr)
307   {
308     theFuncPtr = (FuncType_t )findProc (theFuncName);
309     if (theFuncPtr == NULL)
310     {
311       theLastFailFuncName = theFuncName;
312       return Standard_False;
313     }
314     return Standard_True;
315   }
316
317   //! Auxiliary template to retrieve GL function pointer.
318   //! Same as FindProcVerbose() but without auxiliary last function name argument.
319   template <typename FuncType_t>
320   Standard_Boolean FindProc (const char* theFuncName,
321                              FuncType_t& theFuncPtr)
322   {
323     theFuncPtr = (FuncType_t )findProc (theFuncName);
324     return (theFuncPtr != NULL);
325   }
326
327   //! Return active graphics library.
328   Aspect_GraphicsLibrary GraphicsLibrary() const { return myGapi; }
329
330   //! @return true if detected GL version is greater or equal to requested one.
331   inline Standard_Boolean IsGlGreaterEqual (const Standard_Integer theVerMajor,
332                                             const Standard_Integer theVerMinor) const
333   {
334     return (myGlVerMajor >  theVerMajor)
335         || (myGlVerMajor == theVerMajor && myGlVerMinor >= theVerMinor);
336   }
337
338   //! Return cached GL version major number.
339   Standard_Integer VersionMajor() const { return myGlVerMajor; }
340
341   //! Return cached GL version minor number.
342   Standard_Integer VersionMinor() const { return myGlVerMinor; }
343
344   //! Access entire map of loaded OpenGL functions.
345   const OpenGl_GlFunctions* Functions() const { return myFuncs.get(); }
346
347   //! Clean up errors stack for this GL context (glGetError() in loop).
348   //! @return true if some error has been cleared
349   Standard_EXPORT bool ResetErrors (const bool theToPrintErrors = false);
350
351   //! This method uses system-dependent API to retrieve information
352   //! about GL context bound to the current thread.
353   //! @return true if current thread is bound to this GL context
354   Standard_EXPORT Standard_Boolean IsCurrent() const;
355
356   //! Activates current context.
357   //! Class should be initialized with appropriate info.
358   Standard_EXPORT Standard_Boolean MakeCurrent();
359
360   //! Swap front/back buffers for this GL context (should be activated before!).
361   Standard_EXPORT void SwapBuffers();
362
363   //! Setup swap interval (VSync).
364   Standard_EXPORT Standard_Boolean SetSwapInterval (const Standard_Integer theInterval);
365
366   //! Return true if active mode is GL_RENDER (cached state)
367   Standard_EXPORT Standard_Boolean IsRender() const;
368
369   //! Return true if active mode is GL_FEEDBACK (cached state)
370   Standard_EXPORT Standard_Boolean IsFeedback() const;
371
372   //! This function retrieves information from GL about free GPU memory that is:
373   //!  - OS-dependent. On some OS it is per-process and on others - for entire system.
374   //!  - Vendor-dependent. Currently available only on NVIDIA and AMD/ATi drivers only.
375   //!  - Numbers meaning may vary.
376   //! You should use this info only for diagnostics purposes.
377   //! @return free GPU dedicated memory in bytes.
378   Standard_EXPORT Standard_Size AvailableMemory() const;
379
380   //! This function retrieves information from GL about GPU memory
381   //! and contains more vendor-specific values than AvailableMemory().
382   Standard_EXPORT TCollection_AsciiString MemoryInfo() const;
383
384   //! This function retrieves information from GL about GPU memory.
385   Standard_EXPORT void MemoryInfo (TColStd_IndexedDataMapOfStringString& theDict) const;
386
387   //! Fill in the dictionary with OpenGL info.
388   //! Should be called with bound context.
389   Standard_EXPORT void DiagnosticInformation (TColStd_IndexedDataMapOfStringString& theDict,
390                                               Graphic3d_DiagnosticInfo theFlags) const;
391
392   //! Fetches information about window buffer pixel format.
393   Standard_EXPORT void WindowBufferBits (Graphic3d_Vec4i& theColorBits,
394                                          Graphic3d_Vec2i& theDepthStencilBits) const;
395
396   //! Access shared resource by its name.
397   //! @param  theKey - unique identifier;
398   //! @return handle to shared resource or NULL.
399   Standard_EXPORT const Handle(OpenGl_Resource)& GetResource (const TCollection_AsciiString& theKey) const;
400
401   //! Access shared resource by its name.
402   //! @param  theKey   - unique identifier;
403   //! @param  theValue - handle to fill;
404   //! @return true if resource was shared.
405   template<typename TheHandleType>
406   Standard_Boolean GetResource (const TCollection_AsciiString& theKey,
407                                 TheHandleType&                 theValue) const
408   {
409     const Handle(OpenGl_Resource)& aResource = GetResource (theKey);
410     if (aResource.IsNull())
411     {
412       return Standard_False;
413     }
414
415     theValue = TheHandleType::DownCast (aResource);
416     return !theValue.IsNull();
417   }
418
419   //! Register shared resource.
420   //! Notice that after registration caller shouldn't release it by himself -
421   //! it will be automatically released on context destruction.
422   //! @param theKey      - unique identifier, shouldn't be empty;
423   //! @param theResource - new resource to register, shouldn't be NULL.
424   Standard_EXPORT Standard_Boolean ShareResource (const TCollection_AsciiString& theKey,
425                                                   const Handle(OpenGl_Resource)& theResource);
426
427   //! Release shared resource.
428   //! If there are more than one reference to this resource
429   //! (also used by some other existing object) then call will be ignored.
430   //! This means that current object itself should nullify handle before this call.
431   //! Notice that this is unrecommended operation at all and should be used
432   //! only in case of fat resources to release memory for other needs.
433   //! @param theKey     unique identifier
434   //! @param theToDelay postpone release until next redraw call
435   Standard_EXPORT void ReleaseResource (const TCollection_AsciiString& theKey,
436                                         const Standard_Boolean         theToDelay = Standard_False);
437
438   //! Append resource to queue for delayed clean up.
439   //! Resources in this queue will be released at next redraw call.
440   template <class T>
441   void DelayedRelease (Handle(T)& theResource)
442   {
443     myUnusedResources->Prepend (theResource);
444     theResource.Nullify();
445   }
446
447   //! Clean up the delayed release queue.
448   Standard_EXPORT void ReleaseDelayed();
449
450   //! Return map of shared resources.
451   const OpenGl_ResourcesMap& SharedResources() const { return *mySharedResources; }
452
453   //! @return tool for management of clippings within this context.
454   inline OpenGl_Clipping& ChangeClipping() { return myClippingState; }
455
456   //! @return tool for management of clippings within this context.
457   inline const OpenGl_Clipping& Clipping() const { return myClippingState; }
458
459   //! @return tool for management of shader programs within this context.
460   inline const Handle(OpenGl_ShaderManager)& ShaderManager() const { return myShaderManager; }
461
462 public:
463
464   //! Either GL_CLAMP_TO_EDGE (1.2+) or GL_CLAMP (1.1).
465   Standard_Integer TextureWrapClamp() const { return myTexClamp; }
466
467   //! @return true if texture parameters GL_TEXTURE_BASE_LEVEL/GL_TEXTURE_MAX_LEVEL are supported.
468   Standard_Boolean HasTextureBaseLevel() const
469   {
470     return myGapi == Aspect_GraphicsLibrary_OpenGLES
471          ? IsGlGreaterEqual (3, 0)
472          : IsGlGreaterEqual (1, 2);
473   }
474
475   //! Return map of supported texture formats.
476   const Handle(Image_SupportedFormats)& SupportedTextureFormats() const { return mySupportedFormats; }
477
478   //! @return maximum degree of anisotropy texture filter
479   Standard_Integer MaxDegreeOfAnisotropy() const { return myAnisoMax; }
480
481   //! @return value for GL_MAX_TEXTURE_SIZE
482   Standard_Integer MaxTextureSize() const { return myMaxTexDim; }
483
484   //! @return value for GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS
485   Standard_Integer MaxCombinedTextureUnits() const { return myMaxTexCombined; }
486
487   //! This method returns the multi-texture limit for obsolete fixed-function pipeline.
488   //! Use MaxCombinedTextureUnits() instead for limits for using programmable pipeline.
489   //! @return value for GL_MAX_TEXTURE_UNITS
490   Standard_Integer MaxTextureUnitsFFP() const { return myMaxTexUnitsFFP; }
491
492   //! Return texture unit to be used for sprites (Graphic3d_TextureUnit_PointSprite by default).
493   Graphic3d_TextureUnit SpriteTextureUnit() const { return mySpriteTexUnit; }
494
495   //! @return true if MSAA textures are supported.
496   Standard_Boolean HasTextureMultisampling() const { return myHasMsaaTextures; }
497
498   //! @return value for GL_MAX_SAMPLES
499   Standard_Integer MaxMsaaSamples() const { return myMaxMsaaSamples; }
500
501   //! @return maximum FBO width for image dump
502   Standard_Integer MaxDumpSizeX() const { return myMaxDumpSizeX; }
503
504   //! @return maximum FBO height for image dump
505   Standard_Integer MaxDumpSizeY() const { return myMaxDumpSizeY; }
506
507   //! @return value for GL_MAX_DRAW_BUFFERS
508   Standard_Integer MaxDrawBuffers() const { return myMaxDrawBuffers; }
509
510   //! @return value for GL_MAX_COLOR_ATTACHMENTS
511   Standard_Integer MaxColorAttachments() const { return myMaxColorAttachments; }
512
513   //! Get maximum number of clip planes supported by OpenGl.
514   //! This value is implementation dependent. At least 6
515   //! planes should be supported by OpenGl (see specs).
516   //! @return value for GL_MAX_CLIP_PLANES
517   Standard_Integer MaxClipPlanes() const { return myMaxClipPlanes; }
518
519   //! @return TRUE if ray tracing mode is supported
520   Standard_Boolean HasRayTracing() const { return myHasRayTracing; }
521
522   //! @return TRUE if textures in ray tracing mode are supported
523   Standard_Boolean HasRayTracingTextures() const { return myHasRayTracingTextures; }
524
525   //! @return TRUE if adaptive screen sampling in ray tracing mode is supported
526   Standard_Boolean HasRayTracingAdaptiveSampling() const { return myHasRayTracingAdaptiveSampling; }
527
528   //! @return TRUE if atomic adaptive screen sampling in ray tracing mode is supported
529   Standard_Boolean HasRayTracingAdaptiveSamplingAtomic() const { return myHasRayTracingAdaptiveSamplingAtomic; }
530
531   //! Returns TRUE if sRGB rendering is supported.
532   bool HasSRGB() const
533   {
534     return hasTexSRGB
535        &&  hasFboSRGB;
536   }
537
538   //! Returns TRUE if sRGB rendering is supported and permitted.
539   bool ToRenderSRGB() const
540   {
541     return HasSRGB()
542        && !caps->sRGBDisable
543        && !caps->ffpEnable;
544   }
545
546   //! Returns TRUE if window/surface buffer is sRGB-ready.
547   //!
548   //! When offscreen FBOs are created in sRGB, but window is not sRGB-ready,
549   //! blitting into window should be done with manual gamma correction.
550   //!
551   //! In desktop OpenGL, window buffer can be considered as sRGB-ready by default,
552   //! even when application has NOT requested sRGB-ready pixel format,
553   //! and rendering is managed via GL_FRAMEBUFFER_SRGB state.
554   //!
555   //! In OpenGL ES, sRGB-ready window surface should be explicitly requested on construction,
556   //! and cannot be disabled/enabled without GL_EXT_sRGB_write_control extension afterwards
557   //! (GL_FRAMEBUFFER_SRGB can be considered as always tuned ON).
558   bool IsWindowSRGB() const { return myIsSRgbWindow; }
559
560   //! Overrides if window/surface buffer is sRGB-ready or not (initialized with the context).
561   void SetWindowSRGB (bool theIsSRgb) { myIsSRgbWindow = theIsSRgb; }
562
563   //! Returns TRUE if window/surface buffer has deep color (10bit per component / 30bit RGB) or better precision.
564   bool IsWindowDeepColor() const { return myIsWindowDeepColor; }
565
566   //! Convert Quantity_ColorRGBA into vec4
567   //! with conversion or no conversion into non-linear sRGB
568   //! basing on ToRenderSRGB() flag.
569   OpenGl_Vec4 Vec4FromQuantityColor (const OpenGl_Vec4& theColor) const
570   {
571     return myIsSRgbActive
572          ? Vec4LinearFromQuantityColor(theColor)
573          : Vec4sRGBFromQuantityColor  (theColor);
574   }
575
576   //! Convert Quantity_ColorRGBA into vec4.
577   //! Quantity_Color is expected to be linear RGB, hence conversion is NOT required
578   const OpenGl_Vec4& Vec4LinearFromQuantityColor (const OpenGl_Vec4& theColor) const { return theColor; }
579
580   //! Convert Quantity_ColorRGBA (linear RGB) into non-linear sRGB vec4.
581   OpenGl_Vec4 Vec4sRGBFromQuantityColor (const OpenGl_Vec4& theColor) const
582   {
583     return Quantity_ColorRGBA::Convert_LinearRGB_To_sRGB (theColor);
584   }
585
586   //! Returns TRUE if PBR shading model is supported.
587   //! Basically, feature requires OpenGL 3.0+ / OpenGL ES 3.0+ hardware; more precisely:
588   //! - Graphics hardware with moderate capabilities for compiling long enough GLSL program.
589   //! - FBO (e.g. for baking environment).
590   //! - Multi-texturing with >= 4 units (LUT and IBL textures).
591   //! - GL_RG32F texture format (arbTexRG + arbTexFloat)
592   //! - Cubemap texture lookup textureCubeLod()/textureLod() with LOD index within Fragment Shader,
593   //!   which requires GLSL OpenGL 3.0+ / OpenGL ES 3.0+ or OpenGL 2.1 + GL_EXT_gpu_shader4 extension.
594   Standard_Boolean HasPBR() const { return myHasPBR; }
595
596   //! Returns texture unit where Environment Lookup Table is expected to be bound, or 0 if PBR is unavailable.
597   Graphic3d_TextureUnit PBREnvLUTTexUnit() const { return myPBREnvLUTTexUnit; }
598
599   //! Returns texture unit where Diffuse (irradiance) IBL map's spherical harmonics coefficients is expected to be bound, or 0 if PBR is unavailable.
600   Graphic3d_TextureUnit PBRDiffIBLMapSHTexUnit() const { return myPBRDiffIBLMapSHTexUnit; }
601
602   //! Returns texture unit where Specular IBL map is expected to be bound, or 0 if PBR is unavailable.
603   Graphic3d_TextureUnit PBRSpecIBLMapTexUnit() const { return myPBRSpecIBLMapTexUnit; }
604
605   //! Returns texture unit where shadow map is expected to be bound, or 0 if unavailable.
606   Graphic3d_TextureUnit ShadowMapTexUnit() const { return myShadowMapTexUnit; }
607
608   //! Returns texture unit for occDepthPeelingDepth within enabled Depth Peeling.
609   Graphic3d_TextureUnit DepthPeelingDepthTexUnit() const { return myDepthPeelingDepthTexUnit; }
610
611   //! Returns texture unit for occDepthPeelingFrontColor within enabled Depth Peeling.
612   Graphic3d_TextureUnit DepthPeelingFrontColorTexUnit() const { return myDepthPeelingFrontColorTexUnit; }
613
614   //! Returns true if VBO is supported and permitted.
615   inline bool ToUseVbo() const
616   {
617     return core15fwd != NULL
618        && !caps->vboDisable;
619   }
620
621   //! @return cached state of GL_NORMALIZE.
622   Standard_Boolean IsGlNormalizeEnabled() const { return myIsGlNormalizeEnabled; }
623
624   //! Sets GL_NORMALIZE enabled or disabled.
625   //! @return old value of the flag
626   Standard_EXPORT Standard_Boolean SetGlNormalizeEnabled (Standard_Boolean isEnabled);
627
628   //! @return cached state of polygon rasterization mode (glPolygonMode()).
629   Standard_Integer PolygonMode() const { return myPolygonMode; }
630
631   //! Sets polygon rasterization mode (glPolygonMode() function).
632   //! @return old value of the rasterization mode.
633   Standard_EXPORT Standard_Integer SetPolygonMode (const Standard_Integer theMode);
634
635   //! @return cached enabled state of polygon hatching rasterization.
636   bool IsPolygonHatchEnabled() const { return myHatchIsEnabled; }
637
638   //! Sets enabled state of polygon hatching rasterization
639   //! without affecting currently selected hatching pattern.
640   //! @return previous state of polygon hatching mode.
641   Standard_EXPORT bool SetPolygonHatchEnabled (const bool theIsEnabled);
642
643   //! @return cached state of polygon hatch type.
644   Standard_Integer PolygonHatchStyle() const { return myActiveHatchType; }
645
646   //! Sets polygon hatch pattern.
647   //! Zero-index value is a default alias for solid filling.
648   //! @param theStyle type of hatch supported by base implementation of
649   //! OpenGl_LineAttributes (Aspect_HatchStyle) or the type supported by custom
650   //! implementation derived from OpenGl_LineAttributes class.
651   //! @return old type of hatch.
652   Standard_EXPORT Standard_Integer SetPolygonHatchStyle (const Handle(Graphic3d_HatchStyle)& theStyle);
653
654   //! Sets and applies current polygon offset.
655   Standard_EXPORT void SetPolygonOffset (const Graphic3d_PolygonOffset& theOffset);
656
657   //! Returns currently applied polygon offset parameters.
658   const Graphic3d_PolygonOffset& PolygonOffset() const { return myPolygonOffset; }
659
660   //! Returns camera object.
661   const Handle(Graphic3d_Camera)& Camera() const { return myCamera; }
662
663   //! Sets camera object to the context and update matrices.
664   Standard_EXPORT void SetCamera (const Handle(Graphic3d_Camera)& theCamera);
665
666   //! Applies matrix into shader manager stored in ModelWorldState to OpenGl.
667   //! In "model -> world -> view -> projection" it performs:
668   //!     model -> world
669   Standard_EXPORT void ApplyModelWorldMatrix();
670
671   //! Applies matrix stored in WorldViewState to OpenGl.
672   //! In "model -> world -> view -> projection" it performs:
673   //!     model -> world -> view,
674   //! where model -> world is identical matrix
675   Standard_EXPORT void ApplyWorldViewMatrix();
676
677   //! Applies combination of matrices stored in ModelWorldState and WorldViewState to OpenGl.
678   //! In "model -> world -> view -> projection" it performs:
679   //!     model -> world -> view
680   Standard_EXPORT void ApplyModelViewMatrix();
681
682   //! Applies matrix stored in ProjectionState to OpenGl.
683   //! In "model -> world -> view -> projection" it performs:
684   //!                       view -> projection
685   Standard_EXPORT void ApplyProjectionMatrix();
686
687 public:
688
689   //! @return messenger instance
690   inline const Handle(Message_Messenger)& Messenger() const
691   {
692     return ::Message::DefaultMessenger();
693   }
694
695   //! Callback for GL_ARB_debug_output extension
696   //! @param theSource   message source   within GL_DEBUG_SOURCE_   enumeration
697   //! @param theType     message type     within GL_DEBUG_TYPE_     enumeration
698   //! @param theId       message ID       within source
699   //! @param theSeverity message severity within GL_DEBUG_SEVERITY_ enumeration
700   //! @param theMessage  the message itself
701   Standard_EXPORT void PushMessage (const unsigned int theSource,
702                                     const unsigned int theType,
703                                     const unsigned int theId,
704                                     const unsigned int theSeverity,
705                                     const TCollection_ExtendedString& theMessage);
706
707   //! Adds a filter for messages with theId and theSource (GL_DEBUG_SOURCE_)
708   Standard_EXPORT Standard_Boolean ExcludeMessage (const unsigned int theSource,
709                                                    const unsigned int theId);
710
711   //! Removes a filter for messages with theId and theSource (GL_DEBUG_SOURCE_)
712   Standard_EXPORT Standard_Boolean IncludeMessage (const unsigned int theSource,
713                                                    const unsigned int theId);
714
715   //! @return true if OpenGl context supports left and right rendering buffers.
716   Standard_Boolean HasStereoBuffers() const { return myIsStereoBuffers; }
717
718 public: //! @name methods to alter or retrieve current state
719
720   //! Return structure holding frame statistics.
721   const Handle(OpenGl_FrameStats)& FrameStats() const { return myFrameStats; }
722
723   //! Set structure holding frame statistics.
724   //! This call makes sense only if application defines OpenGl_FrameStats sub-class.
725   void SetFrameStats (const Handle(OpenGl_FrameStats)& theStats) { myFrameStats = theStats; }
726
727   //! Return cached viewport definition (x, y, width, height).
728   const Standard_Integer* Viewport() const { return myViewport; }
729
730   //! Resize the viewport (alias for glViewport).
731   //! @param theRect viewport definition (x, y, width, height)
732   Standard_EXPORT void ResizeViewport (const Standard_Integer theRect[4]);
733
734   //! Return virtual viewport definition (x, y, width, height).
735   const Standard_Integer* VirtualViewport() const { return myViewportVirt; }
736
737   //! Return active read buffer.
738   Standard_Integer ReadBuffer() { return myReadBuffer; }
739
740   //! Switch read buffer, wrapper for ::glReadBuffer().
741   Standard_EXPORT void SetReadBuffer (const Standard_Integer theReadBuffer);
742
743   //! Return active draw buffer attached to a render target referred by index (layout location).
744   Standard_Integer DrawBuffer (Standard_Integer theIndex = 0) const
745   {
746     return theIndex >= myDrawBuffers.Lower()
747         && theIndex <= myDrawBuffers.Upper()
748          ? myDrawBuffers.Value (theIndex)
749          : 0; // GL_NONE
750   }
751
752   //! Switch draw buffer, wrapper for ::glDrawBuffer().
753   Standard_EXPORT void SetDrawBuffer (const Standard_Integer theDrawBuffer);
754
755   //! Switch draw buffer, wrapper for ::glDrawBuffers (GLsizei, const GLenum*).
756   Standard_EXPORT void SetDrawBuffers (const Standard_Integer theNb, const Standard_Integer* theDrawBuffers);
757
758   //! Switch read/draw buffers.
759   void SetReadDrawBuffer (const Standard_Integer theBuffer)
760   {
761     SetReadBuffer (theBuffer);
762     SetDrawBuffer (theBuffer);
763   }
764
765   //! Returns cached GL_FRAMEBUFFER_SRGB state.
766   //! If TRUE, GLSL program is expected to write linear RGB color.
767   //! Otherwise, GLSL program might need manually converting result color into sRGB color space.
768   bool IsFrameBufferSRGB() const { return myIsSRgbActive; }
769
770   //! Enables/disables GL_FRAMEBUFFER_SRGB flag.
771   //! This flag can be set to:
772   //! - TRUE when writing into offscreen FBO (always expected to be in sRGB or RGBF formats).
773   //! - TRUE when writing into sRGB-ready window buffer (might require choosing proper pixel format on window creation).
774   //! - FALSE if sRGB rendering is not supported or sRGB-not-ready window buffer is used for drawing.
775   //! @param[in] theIsFbo flag indicating writing into offscreen FBO (always expected sRGB-ready when sRGB FBO is supported)
776   //!                     or into window buffer (FALSE, sRGB-readiness might vary).
777   //! @param[in] theIsFboSRgb flag indicating off-screen FBO is sRGB-ready
778   Standard_EXPORT void SetFrameBufferSRGB (bool theIsFbo, bool theIsFboSRgb = true);
779
780   //! Return cached flag indicating writing into color buffer is enabled or disabled (glColorMask).
781   const NCollection_Vec4<bool>& ColorMaskRGBA() const { return myColorMask; }
782
783   //! Enable/disable writing into color buffer (wrapper for glColorMask).
784   Standard_EXPORT void SetColorMaskRGBA (const NCollection_Vec4<bool>& theToWriteColor);
785
786   //! Return cached flag indicating writing into color buffer is enabled or disabled (glColorMask).
787   bool ColorMask() const { return myColorMask.r(); }
788
789   //! Enable/disable writing into color buffer (wrapper for glColorMask).
790   //! Alpha component writes will be disabled unconditionally in case of caps->buffersOpaqueAlpha.
791   Standard_EXPORT bool SetColorMask (bool theToWriteColor);
792
793   //! Return TRUE if GL_SAMPLE_ALPHA_TO_COVERAGE usage is allowed.
794   bool AllowSampleAlphaToCoverage() const { return myAllowAlphaToCov; }
795
796   //! Allow GL_SAMPLE_ALPHA_TO_COVERAGE usage.
797   void SetAllowSampleAlphaToCoverage (bool theToEnable) { myAllowAlphaToCov = theToEnable; }
798
799   //! Return GL_SAMPLE_ALPHA_TO_COVERAGE state.
800   bool SampleAlphaToCoverage() const { return myAlphaToCoverage; }
801
802   //! Enable/disable GL_SAMPLE_ALPHA_TO_COVERAGE.
803   Standard_EXPORT bool SetSampleAlphaToCoverage (bool theToEnable);
804
805   //! Return back face culling state.
806   Graphic3d_TypeOfBackfacingModel FaceCulling() const { return myFaceCulling; }
807
808   //! Enable or disable back face culling (glEnable (GL_CULL_FACE)).
809   Standard_EXPORT void SetFaceCulling (Graphic3d_TypeOfBackfacingModel theMode);
810
811   //! Return back face culling state.
812   bool ToCullBackFaces() const { return myFaceCulling == Graphic3d_TypeOfBackfacingModel_BackCulled; }
813
814   //! Enable or disable back face culling (glCullFace() + glEnable(GL_CULL_FACE)).
815   void SetCullBackFaces (bool theToEnable)
816   {
817     SetFaceCulling (theToEnable ? Graphic3d_TypeOfBackfacingModel_BackCulled : Graphic3d_TypeOfBackfacingModel_DoubleSided);
818   }
819
820   //! Fetch OpenGl context state. This class tracks value of several OpenGl
821   //! state variables. Consulting the cached values is quicker than
822   //! doing the same via OpenGl API. Call this method if any of the controlled
823   //! OpenGl state variables has a possibility of being out-of-date.
824   Standard_EXPORT void FetchState();
825
826   //! @return active textures
827   const Handle(OpenGl_TextureSet)& ActiveTextures() const { return myActiveTextures; }
828
829   //! Bind specified texture set to current context taking into account active GLSL program.
830   Standard_DEPRECATED("BindTextures() with explicit GLSL program should be used instead")
831   Handle(OpenGl_TextureSet) BindTextures (const Handle(OpenGl_TextureSet)& theTextures)
832   {
833     return BindTextures (theTextures, myActiveProgram);
834   }
835
836   //! Bind specified texture set to current context, or unbind previous one when NULL specified.
837   //! @param theTextures [in] texture set to bind
838   //! @param theProgram  [in] program attributes; when not NULL,
839   //!                         mock textures will be bound to texture units expected by GLSL program, but undefined by texture set
840   //! @return previous texture set
841   Standard_EXPORT Handle(OpenGl_TextureSet) BindTextures (const Handle(OpenGl_TextureSet)& theTextures,
842                                                           const Handle(OpenGl_ShaderProgram)& theProgram);
843
844   //! @return active GLSL program
845   const Handle(OpenGl_ShaderProgram)& ActiveProgram() const
846   {
847     return myActiveProgram;
848   }
849
850   //! Bind specified program to current context,
851   //! or unbind previous one when NULL specified.
852   //! @return true if some program is bound to context
853   Standard_EXPORT Standard_Boolean BindProgram (const Handle(OpenGl_ShaderProgram)& theProgram);
854
855   //! Setup current shading material.
856   Standard_EXPORT void SetShadingMaterial (const OpenGl_Aspects* theAspect,
857                                            const Handle(Graphic3d_PresentationAttributes)& theHighlight);
858
859   //! Checks if transparency is required for the given aspect and highlight style.
860   Standard_EXPORT static Standard_Boolean CheckIsTransparent (const OpenGl_Aspects* theAspect,
861                                                               const Handle(Graphic3d_PresentationAttributes)& theHighlight,
862                                                               Standard_ShortReal& theAlphaFront,
863                                                               Standard_ShortReal& theAlphaBack);
864
865   //! Checks if transparency is required for the given aspect and highlight style.
866   static Standard_Boolean CheckIsTransparent (const OpenGl_Aspects* theAspect,
867                                               const Handle(Graphic3d_PresentationAttributes)& theHighlight)
868   {
869     Standard_ShortReal anAlphaFront = 1.0f, anAlphaBack = 1.0f;
870     return CheckIsTransparent (theAspect, theHighlight, anAlphaFront, anAlphaBack);
871   }
872
873   //! Setup current color.
874   Standard_EXPORT void SetColor4fv (const OpenGl_Vec4& theColor);
875
876   //! Setup type of line.
877   Standard_EXPORT void SetTypeOfLine (const Aspect_TypeOfLine  theType,
878                                       const Standard_ShortReal theFactor = 1.0f);
879
880   //! Setup stipple line pattern with 1.0f factor; wrapper for glLineStipple().
881   void SetLineStipple (const uint16_t thePattern) { SetLineStipple (1.0f, thePattern); }
882
883   //! Setup type of line; wrapper for glLineStipple().
884   Standard_EXPORT void SetLineStipple (const Standard_ShortReal theFactor,
885                                        const uint16_t thePattern);
886
887   //! Setup width of line.
888   Standard_EXPORT void SetLineWidth (const Standard_ShortReal theWidth);
889
890   //! Setup point size.
891   Standard_EXPORT void SetPointSize (const Standard_ShortReal theSize);
892
893   //! Setup point sprite origin using GL_POINT_SPRITE_COORD_ORIGIN state:
894   //! - GL_UPPER_LEFT when GLSL program is active;
895   //!   flipping should be handled in GLSL program for compatibility with OpenGL ES
896   //! - GL_LOWER_LEFT for FFP
897   Standard_EXPORT void SetPointSpriteOrigin();
898
899   //! Setup texture matrix to active GLSL program or to FFP global state using glMatrixMode (GL_TEXTURE).
900   //! @param theParams    [in] texture parameters
901   //! @param theIsTopDown [in] texture top-down flag
902   Standard_EXPORT void SetTextureMatrix (const Handle(Graphic3d_TextureParams)& theParams,
903                                          const Standard_Boolean theIsTopDown);
904
905   //! Bind default Vertex Array Object
906   Standard_EXPORT void BindDefaultVao();
907
908   //! Default Frame Buffer Object.
909   const Handle(OpenGl_FrameBuffer)& DefaultFrameBuffer() const
910   {
911     return myDefaultFbo;
912   }
913
914   //! Setup new Default Frame Buffer Object and return previously set.
915   //! This call doesn't change Active FBO!
916   Standard_EXPORT Handle(OpenGl_FrameBuffer) SetDefaultFrameBuffer (const Handle(OpenGl_FrameBuffer)& theFbo);
917
918   //! Return debug context initialization state.
919   Standard_Boolean IsDebugContext() const
920   {
921     return myIsGlDebugCtx;
922   }
923
924   Standard_EXPORT void EnableFeatures() const;
925
926   Standard_EXPORT void DisableFeatures() const;
927
928   //! Return resolution for rendering text.
929   unsigned int Resolution() const { return myResolution; }
930
931   //! Resolution scale factor (rendered resolution to standard resolution).
932   //! This scaling factor for parameters like text size to be properly displayed on device (screen / printer).
933   Standard_ShortReal ResolutionRatio() const { return myResolutionRatio; }
934
935   //! Rendering scale factor (rendering viewport height to real window buffer height).
936   Standard_ShortReal RenderScale() const { return myRenderScale; }
937
938   //! Return TRUE if rendering scale factor is not 1.
939   Standard_Boolean HasRenderScale() const { return Abs (myRenderScale - 1.0f) > 0.0001f; }
940
941   //! Rendering scale factor (inverted value).
942   Standard_ShortReal RenderScaleInv() const { return myRenderScaleInv; }
943
944   //! Return scale factor for line width.
945   Standard_ShortReal LineWidthScale() const { return myLineWidthScale; }
946
947   //! Set resolution ratio.
948   //! Note that this method rounds @theRatio to nearest integer.
949   void SetResolution (unsigned int theResolution,
950                       Standard_ShortReal theRatio,
951                       Standard_ShortReal theScale)
952   {
953     myResolution      = (unsigned int )(theScale * theResolution + 0.5f);
954     myRenderScale     = theScale;
955     myRenderScaleInv  = 1.0f / theScale;
956     SetResolutionRatio (theRatio * theScale);
957   }
958
959   //! Set resolution ratio.
960   //! Note that this method rounds @theRatio to nearest integer.
961   void SetResolutionRatio (const Standard_ShortReal theRatio)
962   {
963     myResolutionRatio = theRatio;
964     myLineWidthScale  = Max (1.0f, std::floor (theRatio + 0.5f));
965   }
966
967   //! Return line feater width in pixels.
968   Standard_ShortReal LineFeather() const { return myLineFeather; }
969
970   //! Set line feater width.
971   void SetLineFeather(Standard_ShortReal theValue) { myLineFeather = theValue; }
972
973   //! Wrapper over glGetBufferSubData(), implemented as:
974   //! - OpenGL 1.5+ (desktop) via glGetBufferSubData();
975   //! - OpenGL ES 3.0+ via glMapBufferRange();
976   //! - WebGL 2.0+ via gl.getBufferSubData().
977   //! @param[in]  theTarget target buffer to map {GLenum}
978   //! @param[in]  theOffset offset to the beginning of sub-data {GLintptr}
979   //! @param[in]  theSize   number of bytes to read {GLsizeiptr}
980   //! @param[out] theData   destination pointer to fill
981   //! @return FALSE if functionality is unavailable
982   Standard_EXPORT bool GetBufferSubData (unsigned int theTarget, intptr_t theOffset, intptr_t theSize, void* theData);
983
984   //! Return Graphics Driver's vendor.
985   const TCollection_AsciiString& Vendor() const { return myVendor; }
986
987   //! Dumps the content of me into the stream
988   Standard_EXPORT void DumpJson (Standard_OStream& theOStream, Standard_Integer theDepth = -1) const;
989     
990   //! Dumps the content of openGL state into the stream
991   Standard_EXPORT void DumpJsonOpenGlState (Standard_OStream& theOStream, Standard_Integer theDepth = -1);
992
993   //! Set GL_SHADE_MODEL value.
994   Standard_EXPORT void SetShadeModel (Graphic3d_TypeOfShadingModel theModel);
995
996 private:
997
998   //! Wrapper to system function to retrieve GL function pointer by name.
999   Standard_EXPORT void* findProc (const char* theFuncName);
1000
1001   //! Print error if not all functions have been exported by context for reported version.
1002   //! Note that this will never happen when using GLX, since returned functions can not be validated.
1003   //! @param theGlVerMajor the OpenGL major version with missing functions
1004   //! @param theGlVerMinor the OpenGL minor version with missing functions
1005   //! @param theLastFailedProc function name which cannot be found
1006   Standard_EXPORT void checkWrongVersion (Standard_Integer theGlVerMajor, Standard_Integer theGlVerMinor,
1007                                           const char* theLastFailedProc);
1008
1009   //! Private initialization function that should be called only once.
1010   Standard_EXPORT void init (const Standard_Boolean theIsCoreProfile);
1011
1012 public: //! @name core profiles
1013
1014   OpenGl_GlCore11*     core11ffp;  //!< OpenGL 1.1 core functionality
1015   OpenGl_GlCore11Fwd*  core11fwd;  //!< OpenGL 1.1 without deprecated entry points
1016   OpenGl_GlCore15*     core15;     //!< OpenGL 1.5 without deprecated entry points
1017   OpenGl_GlCore20*     core20;     //!< OpenGL 2.0 without deprecated entry points
1018   OpenGl_GlCore30*     core30;     //!< OpenGL 3.0 without deprecated entry points
1019   OpenGl_GlCore32*     core32;     //!< OpenGL 3.2 core profile
1020   OpenGl_GlCore33*     core33;     //!< OpenGL 3.3 core profile
1021   OpenGl_GlCore41*     core41;     //!< OpenGL 4.1 core profile
1022   OpenGl_GlCore42*     core42;     //!< OpenGL 4.2 core profile
1023   OpenGl_GlCore43*     core43;     //!< OpenGL 4.3 core profile
1024   OpenGl_GlCore44*     core44;     //!< OpenGL 4.4 core profile
1025   OpenGl_GlCore45*     core45;     //!< OpenGL 4.5 core profile
1026   OpenGl_GlCore46*     core46;     //!< OpenGL 4.6 core profile
1027
1028   OpenGl_GlCore15*     core15fwd;  //!< obsolete entry left for code portability; core15 should be used instead
1029   OpenGl_GlCore20*     core20fwd;  //!< obsolete entry left for code portability; core20 should be used instead
1030
1031   Handle(OpenGl_Caps) caps; //!< context options
1032
1033 public: //! @name extensions
1034
1035   Standard_Boolean       hasGetBufferData;   //!< flag indicating if GetBufferSubData() is supported
1036   Standard_Boolean       hasPackRowLength;   //!< supporting of GL_PACK_ROW_LENGTH   parameters (any desktop OpenGL; OpenGL ES 3.0)
1037   Standard_Boolean       hasUnpackRowLength; //!< supporting of GL_UNPACK_ROW_LENGTH parameters (any desktop OpenGL; OpenGL ES 3.0)
1038   Standard_Boolean       hasHighp;           //!< highp in GLSL ES fragment shader is supported
1039   Standard_Boolean       hasUintIndex;       //!< GLuint for index buffer is supported (always available on desktop; on OpenGL ES - since 3.0 or as extension GL_OES_element_index_uint)
1040   Standard_Boolean       hasTexRGBA8;        //!< always available on desktop; on OpenGL ES - since 3.0 or as extension GL_OES_rgb8_rgba8
1041   Standard_Boolean       hasTexFloatLinear;  //!< texture-filterable state for 32-bit floating texture formats (always on desktop, GL_OES_texture_float_linear within OpenGL ES)
1042   Standard_Boolean       hasTexSRGB;         //!< sRGB texture    formats (desktop OpenGL 2.1, OpenGL ES 3.0 or OpenGL ES 2.0 + GL_EXT_sRGB)
1043   Standard_Boolean       hasFboSRGB;         //!< sRGB FBO render targets (desktop OpenGL 2.1, OpenGL ES 3.0)
1044   Standard_Boolean       hasSRGBControl;     //!< sRGB write control (any desktop OpenGL, OpenGL ES + GL_EXT_sRGB_write_control extension)
1045   Standard_Boolean       hasFboRenderMipmap; //!< FBO render target could be non-zero mipmap level of texture
1046   OpenGl_FeatureFlag     hasFlatShading;     //!< Complex flag indicating support of Flat shading (Graphic3d_TypeOfShadingModel_Phong) (always available on desktop; on OpenGL ES - since 3.0 or as extension GL_OES_standard_derivatives)
1047   OpenGl_FeatureFlag     hasGlslBitwiseOps;  //!< GLSL supports bitwise operations; OpenGL 3.0 / OpenGL ES 3.0 (GLSL 130 / GLSL ES 300) or OpenGL 2.1 + GL_EXT_gpu_shader4
1048   OpenGl_FeatureFlag     hasDrawBuffers;     //!< Complex flag indicating support of multiple draw buffers (desktop OpenGL 2.0, OpenGL ES 3.0, GL_ARB_draw_buffers, GL_EXT_draw_buffers)
1049   OpenGl_FeatureFlag     hasFloatBuffer;     //!< Complex flag indicating support of float color buffer format (desktop OpenGL 3.0, GL_ARB_color_buffer_float, GL_EXT_color_buffer_float)
1050   OpenGl_FeatureFlag     hasHalfFloatBuffer; //!< Complex flag indicating support of half-float color buffer format (desktop OpenGL 3.0, GL_ARB_color_buffer_float, GL_EXT_color_buffer_half_float)
1051   OpenGl_FeatureFlag     hasSampleVariables; //!< Complex flag indicating support of MSAA variables in GLSL shader (desktop OpenGL 4.0, GL_ARB_sample_shading)
1052   OpenGl_FeatureFlag     hasGeometryStage;   //!< Complex flag indicating support of Geometry shader (desktop OpenGL 3.2, OpenGL ES 3.2, GL_EXT_geometry_shader)
1053   Standard_Boolean       arbDrawBuffers;     //!< GL_ARB_draw_buffers
1054   Standard_Boolean       arbNPTW;            //!< GL_ARB_texture_non_power_of_two
1055   Standard_Boolean       arbTexRG;           //!< GL_ARB_texture_rg
1056   Standard_Boolean       arbTexFloat;        //!< GL_ARB_texture_float (on desktop OpenGL - since 3.0 or as extension GL_ARB_texture_float; on OpenGL ES - since 3.0); @sa hasTexFloatLinear for linear filtering support
1057   OpenGl_ArbSamplerObject* arbSamplerObject; //!< GL_ARB_sampler_objects (on desktop OpenGL - since 3.3 or as extension GL_ARB_sampler_objects; on OpenGL ES - since 3.0)
1058   OpenGl_ArbTexBindless* arbTexBindless;     //!< GL_ARB_bindless_texture
1059   OpenGl_ArbTBO*         arbTBO;             //!< GL_ARB_texture_buffer_object (on desktop OpenGL - since 3.1 or as extension GL_ARB_texture_buffer_object; on OpenGL ES - since 3.2)
1060   Standard_Boolean       arbTboRGB32;        //!< GL_ARB_texture_buffer_object_rgb32 (3-component TBO), in core since 4.0 (on OpenGL ES - since 3.2)
1061   Standard_Boolean       arbClipControl;     //!< GL_ARB_clip_control, in core since 4.5
1062   OpenGl_ArbIns*         arbIns;             //!< GL_ARB_draw_instanced (on desktop OpenGL - since 3.1 or as extension GL_ARB_draw_instanced; on OpenGL ES - since 3.0 or as extension GL_ANGLE_instanced_arrays to WebGL 1.0)
1063   OpenGl_ArbDbg*         arbDbg;             //!< GL_ARB_debug_output (on desktop OpenGL - since 4.3 or as extension GL_ARB_debug_output; on OpenGL ES - since 3.2 or as extension GL_KHR_debug)
1064   OpenGl_ArbFBO*         arbFBO;             //!< GL_ARB_framebuffer_object
1065   OpenGl_ArbFBOBlit*     arbFBOBlit;         //!< glBlitFramebuffer function, moved out from OpenGl_ArbFBO structure for compatibility with OpenGL ES 2.0
1066   Standard_Boolean       arbSampleShading;   //!< GL_ARB_sample_shading
1067   Standard_Boolean       arbDepthClamp;      //!< GL_ARB_depth_clamp (on desktop OpenGL - since 3.2 or as extensions GL_ARB_depth_clamp,NV_depth_clamp; unavailable on OpenGL ES)
1068   Standard_Boolean       extFragDepth;       //!< GL_EXT_frag_depth on OpenGL ES 2.0 (gl_FragDepthEXT built-in variable, before OpenGL ES 3.0)
1069   Standard_Boolean       extDrawBuffers;     //!< GL_EXT_draw_buffers
1070   OpenGl_ExtGS*          extGS;              //!< GL_EXT_geometry_shader4
1071   Standard_Boolean       extBgra;            //!< GL_EXT_bgra or GL_EXT_texture_format_BGRA8888 on OpenGL ES
1072   Standard_Boolean       extTexR16;          //!< GL_EXT_texture_norm16 on OpenGL ES; always available on desktop
1073   Standard_Boolean       extAnis;            //!< GL_EXT_texture_filter_anisotropic
1074   Standard_Boolean       extPDS;             //!< GL_EXT_packed_depth_stencil
1075   Standard_Boolean       atiMem;             //!< GL_ATI_meminfo
1076   Standard_Boolean       nvxMem;             //!< GL_NVX_gpu_memory_info
1077   Standard_Boolean       oesSampleVariables; //!< GL_OES_sample_variables
1078   Standard_Boolean       oesStdDerivatives;  //!< GL_OES_standard_derivatives
1079
1080 public: //! @name public properties tracking current state
1081
1082   OpenGl_MatrixState<Standard_ShortReal> ModelWorldState; //!< state of orientation matrix
1083   OpenGl_MatrixState<Standard_ShortReal> WorldViewState;  //!< state of orientation matrix
1084   OpenGl_MatrixState<Standard_ShortReal> ProjectionState; //!< state of projection  matrix
1085
1086 private: // system-dependent fields
1087
1088   Aspect_Drawable         myWindow;   //!< surface           EGLSurface | HWND  | GLXDrawable
1089   Aspect_Display          myDisplay;  //!< display           EGLDisplay | HDC   | Display*
1090   Aspect_RenderingContext myGContext; //!< rendering context EGLContext | HGLRC | GLXContext | EAGLContext* | NSOpenGLContext*
1091
1092 private: // context info
1093
1094   typedef NCollection_Shared< NCollection_DataMap<TCollection_AsciiString, Standard_Integer> > OpenGl_DelayReleaseMap;
1095   typedef NCollection_Shared< NCollection_List<Handle(OpenGl_Resource)> > OpenGl_ResourcesStack;
1096
1097   Handle(OpenGl_ResourcesMap)    mySharedResources; //!< shared resources with unique identification key
1098   Handle(OpenGl_DelayReleaseMap) myDelayed;         //!< shared resources for delayed release
1099   Handle(OpenGl_ResourcesStack)  myUnusedResources; //!< stack of resources for delayed clean up
1100
1101   OpenGl_Clipping myClippingState; //!< state of clip planes
1102
1103   void*            myGlLibHandle;          //!< optional handle to GL library
1104   std::unique_ptr<OpenGl_GlFunctions>
1105                    myFuncs;                //!< mega structure for all GL functions
1106   Aspect_GraphicsLibrary myGapi;           //!< GAPI name
1107   Handle(Image_SupportedFormats)
1108                    mySupportedFormats;     //!< map of supported texture formats
1109   Standard_Integer myAnisoMax;             //!< maximum level of anisotropy texture filter
1110   Standard_Integer myTexClamp;             //!< either GL_CLAMP_TO_EDGE (1.2+) or GL_CLAMP (1.1)
1111   Standard_Integer myMaxTexDim;            //!< value for GL_MAX_TEXTURE_SIZE
1112   Standard_Integer myMaxTexCombined;       //!< value for GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS
1113   Standard_Integer myMaxTexUnitsFFP;       //!< value for GL_MAX_TEXTURE_UNITS (fixed-function pipeline only)
1114   Standard_Integer myMaxDumpSizeX;         //!< maximum FBO width  for image dump
1115   Standard_Integer myMaxDumpSizeY;         //!< maximum FBO height for image dump
1116   Standard_Integer myMaxClipPlanes;        //!< value for GL_MAX_CLIP_PLANES
1117   Standard_Integer myMaxMsaaSamples;       //!< value for GL_MAX_SAMPLES
1118   Standard_Integer myMaxDrawBuffers;       //!< value for GL_MAX_DRAW_BUFFERS
1119   Standard_Integer myMaxColorAttachments;  //!< value for GL_MAX_COLOR_ATTACHMENTS
1120   Standard_Integer myGlVerMajor;           //!< cached GL version major number
1121   Standard_Integer myGlVerMinor;           //!< cached GL version minor number
1122   Standard_Boolean myIsInitialized;        //!< flag indicates initialization state
1123   Standard_Boolean myIsStereoBuffers;      //!< context supports stereo buffering
1124   Standard_Boolean myHasMsaaTextures;      //!< context supports MSAA textures
1125   Standard_Boolean myIsGlNormalizeEnabled; //!< GL_NORMALIZE flag
1126                                            //!< Used to tell OpenGl that normals should be normalized
1127   Graphic3d_TextureUnit mySpriteTexUnit;   //!< sampler2D occSamplerPointSprite, texture unit for point sprite texture
1128
1129   Standard_Boolean myHasRayTracing;                 //! indicates whether ray tracing mode is supported
1130   Standard_Boolean myHasRayTracingTextures;         //! indicates whether textures in ray tracing mode are supported
1131   Standard_Boolean myHasRayTracingAdaptiveSampling; //! indicates whether adaptive screen sampling in ray tracing mode is supported
1132   Standard_Boolean myHasRayTracingAdaptiveSamplingAtomic; //! indicates whether atomic adaptive screen sampling in ray tracing mode is supported
1133
1134   Standard_Boolean myHasPBR;                      //!< indicates whether PBR shading model is supported
1135   Graphic3d_TextureUnit myPBREnvLUTTexUnit;       //!< sampler2D occEnvLUT, texture unit where environment lookup table is expected to be binded (0 if PBR is not supported)
1136   Graphic3d_TextureUnit myPBRDiffIBLMapSHTexUnit; //!< sampler2D occDiffIBLMapSHCoeffs, texture unit where diffuse (irradiance) IBL map's spherical harmonics coefficients is expected to  be binded
1137                                                   //!  (0 if PBR is not supported)
1138   Graphic3d_TextureUnit myPBRSpecIBLMapTexUnit;   //!< samplerCube occSpecIBLMap, texture unit where specular IBL map is expected to  be binded (0 if PBR is not supported)
1139   Graphic3d_TextureUnit myShadowMapTexUnit;       //!< sampler2D occShadowMapSampler
1140
1141   Graphic3d_TextureUnit myDepthPeelingDepthTexUnit;      //!< sampler2D occDepthPeelingDepth, texture unit for Depth Peeling lookups
1142   Graphic3d_TextureUnit myDepthPeelingFrontColorTexUnit; //!< sampler2D occDepthPeelingFrontColor, texture unit for Depth Peeling lookups
1143
1144   Handle(OpenGl_ShaderManager) myShaderManager; //! support object for managing shader programs
1145
1146 private: //! @name fields tracking current state
1147
1148   Handle(Graphic3d_Camera)      myCamera;          //!< active camera object
1149   Handle(OpenGl_FrameStats)     myFrameStats;      //!< structure accumulating frame statistics
1150   Handle(OpenGl_ShaderProgram)  myActiveProgram;   //!< currently active GLSL program
1151   Handle(OpenGl_TextureSet)     myActiveTextures;  //!< currently bound textures
1152                                                    //!< currently active sampler objects
1153   Standard_Integer              myActiveMockTextures; //!< currently active mock sampler objects
1154   Handle(OpenGl_FrameBuffer)    myDefaultFbo;      //!< default Frame Buffer Object
1155   Handle(OpenGl_LineAttributes) myHatchStyles;     //!< resource holding predefined hatch styles patterns
1156   Standard_Integer              myActiveHatchType; //!< currently activated type of polygon hatch
1157   Standard_Boolean              myHatchIsEnabled;  //!< current enabled state of polygon hatching rasterization
1158   Handle(OpenGl_Texture)        myTextureRgbaBlack;//!< mock black texture returning (0, 0, 0, 0)
1159   Handle(OpenGl_Texture)        myTextureRgbaWhite;//!< mock white texture returning (1, 1, 1, 1)
1160   Standard_Integer              myViewport[4];     //!< current viewport
1161   Standard_Integer              myViewportVirt[4]; //!< virtual viewport
1162   Standard_Integer              myPointSpriteOrig; //!< GL_POINT_SPRITE_COORD_ORIGIN state (GL_UPPER_LEFT by default)
1163   Standard_Integer              myRenderMode;      //!< value for active rendering mode
1164   Standard_Integer              myShadeModel;      //!< currently used shade model (glShadeModel)
1165   Standard_Integer              myPolygonMode;     //!< currently used polygon rasterization mode (glPolygonMode)
1166   Graphic3d_PolygonOffset       myPolygonOffset;   //!< currently applied polygon offset
1167   Graphic3d_TypeOfBackfacingModel myFaceCulling;   //!< back face culling mode enabled state (glIsEnabled (GL_CULL_FACE))
1168   Standard_Integer              myReadBuffer;      //!< current read buffer
1169   NCollection_Array1<Standard_Integer>
1170                                 myDrawBuffers;     //!< current draw buffers
1171   unsigned int                  myDefaultVao;      //!< default Vertex Array Object
1172   NCollection_Vec4<bool>        myColorMask;       //!< flag indicating writing into color buffer is enabled or disabled (glColorMask)
1173   Standard_Boolean              myAllowAlphaToCov; //!< flag allowing   GL_SAMPLE_ALPHA_TO_COVERAGE usage
1174   Standard_Boolean              myAlphaToCoverage; //!< flag indicating GL_SAMPLE_ALPHA_TO_COVERAGE state
1175   Standard_Boolean              myIsGlDebugCtx;    //!< debug context initialization state
1176   Standard_Boolean              myIsWindowDeepColor; //!< indicates that window buffer is has deep color pixel format
1177   Standard_Boolean              myIsSRgbWindow;    //!< indicates that window buffer is sRGB-ready
1178   Standard_Boolean              myIsSRgbActive;    //!< flag indicating GL_FRAMEBUFFER_SRGB state
1179   TCollection_AsciiString       myVendor;          //!< Graphics Driver's vendor
1180   TColStd_PackedMapOfInteger    myFilters[6];      //!< messages suppressing filter (for sources from GL_DEBUG_SOURCE_API_ARB to GL_DEBUG_SOURCE_OTHER_ARB)
1181   unsigned int                  myResolution;      //!< Pixels density (PPI), defines scaling factor for parameters like text size
1182   Standard_ShortReal            myResolutionRatio; //!< scaling factor for parameters like text size
1183                                                    //!  to be properly displayed on device (screen / printer)
1184   Standard_ShortReal            myLineWidthScale;  //!< scaling factor for line width
1185   Standard_ShortReal            myLineFeather;     //!< line feater width in pixels
1186   Standard_ShortReal            myRenderScale;     //!< scaling factor for rendering resolution
1187   Standard_ShortReal            myRenderScaleInv;  //!< scaling factor for rendering resolution (inverted value)
1188   OpenGl_Material               myMaterial;        //!< current front/back material state (cached to reduce GL context updates)
1189
1190 private:
1191
1192   //! Copying allowed only within Handles
1193   OpenGl_Context            (const OpenGl_Context& );
1194   OpenGl_Context& operator= (const OpenGl_Context& );
1195
1196 };
1197
1198 #endif // _OpenGl_Context_H__