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