0028466: Visualization, OpenGl_Context - read GPU memory using WGL_AMD_gpu_associatio...
[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 <NCollection_Map.hxx>
28 #include <NCollection_Handle.hxx>
29 #include <NCollection_List.hxx>
30 #include <Message.hxx>
31 #include <OpenGl_Caps.hxx>
32 #include <OpenGl_LineAttributes.hxx>
33 #include <OpenGl_Material.hxx>
34 #include <OpenGl_MatrixState.hxx>
35 #include <OpenGl_Vec.hxx>
36 #include <OpenGl_Resource.hxx>
37 #include <Standard_Transient.hxx>
38 #include <TColStd_IndexedDataMapOfStringString.hxx>
39 #include <TColStd_PackedMapOfInteger.hxx>
40 #include <OpenGl_Clipping.hxx>
41 #include <OpenGl_GlCore11.hxx>
42 #include <OpenGl_ShaderProgram.hxx>
43
44 #include <NCollection_Shared.hxx>
45
46 //! Forward declarations
47 #if defined(__APPLE__)
48   #import <TargetConditionals.h>
49   #if defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE
50     #ifdef __OBJC__
51       @class EAGLContext;
52     #else
53       struct EAGLContext;
54     #endif
55   #else
56     #ifdef __OBJC__
57       @class NSOpenGLContext;
58     #else
59       struct NSOpenGLContext;
60     #endif
61   #endif
62 #endif
63
64 struct OpenGl_GlFunctions;
65 struct OpenGl_ArbTBO;
66 struct OpenGl_ArbIns;
67 struct OpenGl_ArbDbg;
68 struct OpenGl_ArbFBO;
69 struct OpenGl_ArbFBOBlit;
70 struct OpenGl_ExtGS;
71 struct OpenGl_ArbTexBindless;
72
73 template<typename theBaseClass_t> struct OpenGl_TmplCore12;
74 typedef OpenGl_TmplCore12<OpenGl_GlCore11>     OpenGl_GlCore12;
75 typedef OpenGl_TmplCore12<OpenGl_GlCore11Fwd>  OpenGl_GlCore12Fwd;
76
77 struct OpenGl_GlCore13;
78 struct OpenGl_GlCore13Fwd;
79
80 template<typename theBaseClass_t> struct OpenGl_TmplCore14;
81 typedef OpenGl_TmplCore14<OpenGl_GlCore13>     OpenGl_GlCore14;
82 typedef OpenGl_TmplCore14<OpenGl_GlCore13Fwd>  OpenGl_GlCore14Fwd;
83
84 template<typename theBaseClass_t> struct OpenGl_TmplCore15;
85 typedef OpenGl_TmplCore15<OpenGl_GlCore14>     OpenGl_GlCore15;
86 typedef OpenGl_TmplCore15<OpenGl_GlCore14Fwd>  OpenGl_GlCore15Fwd;
87
88 template<typename theBaseClass_t> struct OpenGl_TmplCore20;
89 typedef OpenGl_TmplCore20<OpenGl_GlCore15>     OpenGl_GlCore20;
90 typedef OpenGl_TmplCore20<OpenGl_GlCore15Fwd>  OpenGl_GlCore20Fwd;
91
92 template<typename theBaseClass_t> struct OpenGl_TmplCore21;
93 typedef OpenGl_TmplCore21<OpenGl_GlCore20>     OpenGl_GlCore21;
94 typedef OpenGl_TmplCore21<OpenGl_GlCore20Fwd>  OpenGl_GlCore21Fwd;
95
96 template<typename theBaseClass_t> struct OpenGl_TmplCore30;
97 typedef OpenGl_TmplCore30<OpenGl_GlCore21>     OpenGl_GlCore30;
98 typedef OpenGl_TmplCore30<OpenGl_GlCore21Fwd>  OpenGl_GlCore30Fwd;
99
100 template<typename theBaseClass_t> struct OpenGl_TmplCore31;
101 typedef OpenGl_TmplCore31<OpenGl_GlCore30>     OpenGl_GlCore31Back;
102 typedef OpenGl_TmplCore31<OpenGl_GlCore30Fwd>  OpenGl_GlCore31;
103
104 template<typename theBaseClass_t> struct OpenGl_TmplCore32;
105 typedef OpenGl_TmplCore32<OpenGl_GlCore31Back> OpenGl_GlCore32Back;
106 typedef OpenGl_TmplCore32<OpenGl_GlCore31>     OpenGl_GlCore32;
107
108 template<typename theBaseClass_t> struct OpenGl_TmplCore33;
109 typedef OpenGl_TmplCore33<OpenGl_GlCore32Back> OpenGl_GlCore33Back;
110 typedef OpenGl_TmplCore33<OpenGl_GlCore32>     OpenGl_GlCore33;
111
112 template<typename theBaseClass_t> struct OpenGl_TmplCore40;
113 typedef OpenGl_TmplCore40<OpenGl_GlCore33Back> OpenGl_GlCore40Back;
114 typedef OpenGl_TmplCore40<OpenGl_GlCore33>     OpenGl_GlCore40;
115
116 template<typename theBaseClass_t> struct OpenGl_TmplCore41;
117 typedef OpenGl_TmplCore41<OpenGl_GlCore40Back> OpenGl_GlCore41Back;
118 typedef OpenGl_TmplCore41<OpenGl_GlCore40>     OpenGl_GlCore41;
119
120 template<typename theBaseClass_t> struct OpenGl_TmplCore42;
121 typedef OpenGl_TmplCore42<OpenGl_GlCore41Back> OpenGl_GlCore42Back;
122 typedef OpenGl_TmplCore42<OpenGl_GlCore41>     OpenGl_GlCore42;
123
124 template<typename theBaseClass_t> struct OpenGl_TmplCore43;
125 typedef OpenGl_TmplCore43<OpenGl_GlCore42Back> OpenGl_GlCore43Back;
126 typedef OpenGl_TmplCore43<OpenGl_GlCore42>     OpenGl_GlCore43;
127
128 template<typename theBaseClass_t> struct OpenGl_TmplCore44;
129 typedef OpenGl_TmplCore44<OpenGl_GlCore43Back> OpenGl_GlCore44Back;
130 typedef OpenGl_TmplCore44<OpenGl_GlCore43>     OpenGl_GlCore44;
131
132 class OpenGl_ShaderManager;
133 class OpenGl_Sampler;
134 class OpenGl_FrameBuffer;
135 class OpenGl_AspectFace;
136 class Graphic3d_PresentationAttributes;
137
138 DEFINE_STANDARD_HANDLE(OpenGl_Context, Standard_Transient)
139
140 //! This class generalize access to the GL context and available extensions.
141 //!
142 //! Functions related to specific OpenGL version or extension are grouped into structures which can be accessed as fields of this class.
143 //! The most simple way to check that required functionality is available - is NULL check for the group:
144 //! @code
145 //!   if (myContext->core20 != NULL)
146 //!   {
147 //!     myGlProgram = myContext->core20->glCreateProgram();
148 //!     .. do more stuff ..
149 //!   }
150 //!   else
151 //!   {
152 //!     .. compatibility with outdated configurations ..
153 //!   }
154 //! @endcode
155 //!
156 //! Current implementation provide access to OpenGL core functionality up to 4.4 version (core12, core13, core14, core15, fields core20)
157 //! as well as several extensions (arbTBO, arbFBO, etc.).
158 //!
159 //! OpenGL context might be initialized in Core Profile. In this case deprecated functionality become unavailable.
160 //! To make code easily adaptable to wide range of OpenGL versions, function sets related to each version has two kinds of suffixes:
161 //!  - "back" for version 3.2+.
162 //!     Represents function set for Backward-Compatible Profile.
163 //!     Function sets without this suffix represents core profile.
164 //!  - "fwd"  for version 3.0-.
165 //!     Represents non-deprecated function set of earlier OpenGL versions, which are still available within OpenGL 3.2 Core Profile.
166 //!     Function sets without this suffix represents complete list of functions related to specific OpenGL version.
167 //!
168 //! To select which core** function set should be used in specific case:
169 //!  - Determine the minimal OpenGL version required for implemented functionality and use it to access all functions.
170 //!    For example, if algorithm requires OpenGL 2.1+, it is better to write core20fwd->glEnable() rather than core11fwd->glEnable() for uniformity.
171 //!  - If functionality will work within Core Profile, use function sets with appropriate suffix.
172 //!  - Validate minimal requirements at initialization/creation time and omit checks within code where algorithm should be already initialized.
173 //!    Properly escape code incompatible with Core Profile. The simplest way to check Core Profile is "if (core11 == NULL)".
174 //!
175 //! Simplified extensions classification:
176 //!  - prefixed with NV, AMD, ATI are vendor-specific (however may be provided by other vendors in some cases);
177 //!  - prefixed with EXT are accepted by 2+ vendors;
178 //!  - prefixed with ARB are accepted by Architecture Review Board and are candidates
179 //!    for inclusion into GL core functionality.
180 //! Some functionality can be represented in several extensions simultaneously.
181 //! In this case developer should be careful because different specification may differ
182 //! in aspects (like enumeration values and error-handling).
183 //!
184 //! Notice that some systems provide mechanisms to simultaneously incorporate with GL contexts with different capabilities.
185 //! For this reason OpenGl_Context should be initialized and used for each GL context independently.
186 class OpenGl_Context : public Standard_Transient
187 {
188   DEFINE_STANDARD_RTTIEXT(OpenGl_Context, Standard_Transient)
189   friend class OpenGl_Window;
190 public:
191
192   //! Function for getting power of to number larger or equal to input number.
193   //! @param theNumber    number to 'power of two'
194   //! @param theThreshold upper threshold
195   //! @return power of two number
196   inline static Standard_Integer GetPowerOfTwo (const Standard_Integer theNumber,
197                                                 const Standard_Integer theThreshold)
198   {
199     for (Standard_Integer p2 = 2; p2 <= theThreshold; p2 <<= 1)
200     {
201       if (theNumber <= p2)
202       {
203         return p2;
204       }
205     }
206     return theThreshold;
207   }
208
209 public:
210
211   //! Empty constructor. You should call Init() to perform initialization with bound GL context.
212   Standard_EXPORT OpenGl_Context (const Handle(OpenGl_Caps)& theCaps = NULL);
213
214   //! Destructor.
215   Standard_EXPORT virtual ~OpenGl_Context();
216
217   //! Release all resources, including shared ones
218   Standard_EXPORT void forcedRelease();
219
220   //! Share GL context resources.
221   //! theShareCtx - handle to context to retrieve handles to shared resources.
222   Standard_EXPORT void Share (const Handle(OpenGl_Context)& theShareCtx);
223
224   //! Initialize class from currently bound OpenGL context. Method should be called only once.
225   //! @return false if no GL context is bound to the current thread
226   Standard_EXPORT Standard_Boolean Init (const Standard_Boolean theIsCoreProfile = Standard_False);
227
228   //! @return true if this context is valid (has been initialized)
229   inline Standard_Boolean IsValid() const
230   {
231     return myIsInitialized;
232   }
233
234 #if defined(HAVE_EGL)
235   //! Initialize class from specified surface and rendering context. Method should be called only once.
236   //! @return false if OpenGL context can not be bound to specified surface
237   Standard_EXPORT Standard_Boolean Init (const Aspect_Drawable         theEglSurface,
238                                          const Aspect_Display          theEglDisplay,
239                                          const Aspect_RenderingContext theEglContext,
240                                          const Standard_Boolean        theIsCoreProfile = Standard_False);
241 #elif defined(_WIN32)
242   //! Initialize class from specified window and rendering context. Method should be called only once.
243   //! @return false if OpenGL context can not be bound to specified window
244   Standard_EXPORT Standard_Boolean Init (const Aspect_Handle           theWindow,
245                                          const Aspect_Handle           theWindowDC,
246                                          const Aspect_RenderingContext theGContext,
247                                          const Standard_Boolean        theIsCoreProfile = Standard_False);
248
249   //! @return the window handle (HWND) currently bound to this OpenGL context
250   inline Aspect_Handle Window() const
251   {
252     return myWindow;
253   }
254
255 #elif defined(__APPLE__) && !defined(MACOSX_USE_GLX)
256   #if defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE
257
258   //! Initialize class from specified OpenGL ES context (EAGLContext). Method should be called only once.
259   Standard_EXPORT Standard_Boolean Init (EAGLContext*                  theGContext,
260                                          const Standard_Boolean        theIsCoreProfile = Standard_False);
261   #else
262
263   //! Initialize class from specified OpenGL context (NSOpenGLContext). Method should be called only once.
264   Standard_EXPORT Standard_Boolean Init (NSOpenGLContext*              theGContext,
265                                          const Standard_Boolean        theIsCoreProfile = Standard_False);
266   #endif
267 #else
268
269   //! Initialize class from specified window and rendering context. Method should be called only once.
270   //! @return false if OpenGL context can not be bound to specified window
271   Standard_EXPORT Standard_Boolean Init (const Aspect_Drawable         theWindow,
272                                          const Aspect_Display          theDisplay,
273                                          const Aspect_RenderingContext theGContext,
274                                          const Standard_Boolean        theIsCoreProfile = Standard_False);
275
276   //! @return the window handle (GLXDrawable) currently bound to this OpenGL context
277   inline Aspect_Drawable Window() const
278   {
279     return myWindow;
280   }
281 #endif
282
283   //! Read OpenGL version information from active context.
284   Standard_EXPORT static void ReadGlVersion (Standard_Integer& theGlVerMajor,
285                                              Standard_Integer& theGlVerMinor);
286
287   //! Check if theExtName extension is supported by active GL context.
288   Standard_EXPORT Standard_Boolean CheckExtension (const char* theExtName) const;
289
290   //! Check if theExtName extension is in extensions string.
291   Standard_EXPORT static Standard_Boolean CheckExtension (const char* theExtString,
292                                                           const char* theExtName);
293
294   //! Auxiliary template to retrieve GL function pointer.
295   //! Pointer to function retrieved from library is statically casted
296   //! to requested type - there no way to check real signature of exported function.
297   //! The context should be bound before call.
298   template <typename FuncType_t>
299   Standard_Boolean FindProc (const char* theFuncName,
300                              FuncType_t& theFuncPtr)
301   {
302     theFuncPtr = (FuncType_t )findProc (theFuncName);
303     return (theFuncPtr != NULL);
304   }
305
306   //! @return true if detected GL version is greater or equal to requested one.
307   inline Standard_Boolean IsGlGreaterEqual (const Standard_Integer theVerMajor,
308                                             const Standard_Integer theVerMinor) const
309   {
310     return (myGlVerMajor >  theVerMajor)
311         || (myGlVerMajor == theVerMajor && myGlVerMinor >= theVerMinor);
312   }
313
314   //! Return cached GL version major number.
315   Standard_Integer VersionMajor() const { return myGlVerMajor; }
316
317   //! Return cached GL version minor number.
318   Standard_Integer VersionMinor() const { return myGlVerMinor; }
319
320   //! Access entire map of loaded OpenGL functions.
321   const OpenGl_GlFunctions* Functions() const { return myFuncs.operator->(); }
322
323   //! Clean up errors stack for this GL context (glGetError() in loop).
324   //! @return true if some error has been cleared
325   Standard_EXPORT bool ResetErrors (const bool theToPrintErrors = false);
326
327   //! This method uses system-dependent API to retrieve information
328   //! about GL context bound to the current thread.
329   //! @return true if current thread is bound to this GL context
330   Standard_EXPORT Standard_Boolean IsCurrent() const;
331
332   //! Activates current context.
333   //! Class should be initialized with appropriate info.
334   Standard_EXPORT Standard_Boolean MakeCurrent();
335
336   //! Swap front/back buffers for this GL context (should be activated before!).
337   Standard_EXPORT void SwapBuffers();
338
339   //! Setup swap interval (VSync).
340   Standard_EXPORT Standard_Boolean SetSwapInterval (const Standard_Integer theInterval);
341
342   //! Return true if active mode is GL_RENDER (cached state)
343   Standard_Boolean IsRender() const
344   {
345   #if !defined(GL_ES_VERSION_2_0)
346     return myRenderMode == GL_RENDER;
347   #else
348     return Standard_True;
349   #endif
350   }
351
352   //! Return true if active mode is GL_FEEDBACK (cached state)
353   Standard_Boolean IsFeedback() const
354   {
355   #if !defined(GL_ES_VERSION_2_0)
356     return myRenderMode == GL_FEEDBACK;
357   #else
358     return Standard_False;
359   #endif
360   }
361
362   //! This function retrieves information from GL about free GPU memory that is:
363   //!  - OS-dependent. On some OS it is per-process and on others - for entire system.
364   //!  - Vendor-dependent. Currently available only on NVIDIA and AMD/ATi drivers only.
365   //!  - Numbers meaning may vary.
366   //! You should use this info only for diagnostics purposes.
367   //! @return free GPU dedicated memory in bytes.
368   Standard_EXPORT Standard_Size AvailableMemory() const;
369
370   //! This function retrieves information from GL about GPU memory
371   //! and contains more vendor-specific values than AvailableMemory().
372   Standard_EXPORT TCollection_AsciiString MemoryInfo() const;
373
374   //! This function retrieves information from GL about GPU memory.
375   Standard_EXPORT void MemoryInfo (TColStd_IndexedDataMapOfStringString& theDict) const;
376
377   //! Fill in the dictionary with OpenGL info.
378   //! Should be called with bound context.
379   Standard_EXPORT void DiagnosticInformation (TColStd_IndexedDataMapOfStringString& theDict,
380                                               Graphic3d_DiagnosticInfo theFlags) const;
381
382   //! Access shared resource by its name.
383   //! @param  theKey - unique identifier;
384   //! @return handle to shared resource or NULL.
385   Standard_EXPORT const Handle(OpenGl_Resource)& GetResource (const TCollection_AsciiString& theKey) const;
386
387   //! Access shared resource by its name.
388   //! @param  theKey   - unique identifier;
389   //! @param  theValue - handle to fill;
390   //! @return true if resource was shared.
391   template<typename TheHandleType>
392   Standard_Boolean GetResource (const TCollection_AsciiString& theKey,
393                                 TheHandleType&                 theValue) const
394   {
395     const Handle(OpenGl_Resource)& aResource = GetResource (theKey);
396     if (aResource.IsNull())
397     {
398       return Standard_False;
399     }
400
401     theValue = TheHandleType::DownCast (aResource);
402     return !theValue.IsNull();
403   }
404
405   //! Register shared resource.
406   //! Notice that after registration caller shouldn't release it by himself -
407   //! it will be automatically released on context destruction.
408   //! @param theKey      - unique identifier, shouldn't be empty;
409   //! @param theResource - new resource to register, shouldn't be NULL.
410   Standard_EXPORT Standard_Boolean ShareResource (const TCollection_AsciiString& theKey,
411                                                   const Handle(OpenGl_Resource)& theResource);
412
413   //! Release shared resource.
414   //! If there are more than one reference to this resource
415   //! (also used by some other existing object) then call will be ignored.
416   //! This means that current object itself should nullify handle before this call.
417   //! Notice that this is unrecommended operation at all and should be used
418   //! only in case of fat resources to release memory for other needs.
419   //! @param theKey     unique identifier
420   //! @param theToDelay postpone release until next redraw call
421   Standard_EXPORT void ReleaseResource (const TCollection_AsciiString& theKey,
422                                         const Standard_Boolean         theToDelay = Standard_False);
423
424   //! Append resource to queue for delayed clean up.
425   //! Resources in this queue will be released at next redraw call.
426   template <class T>
427   void DelayedRelease (Handle(T)& theResource)
428   {
429     myUnusedResources->Prepend (theResource);
430     theResource.Nullify();
431   }
432
433   //! Clean up the delayed release queue.
434   Standard_EXPORT void ReleaseDelayed();
435
436   //! @return tool for management of clippings within this context.
437   inline OpenGl_Clipping& ChangeClipping() { return myClippingState; }
438
439   //! @return tool for management of clippings within this context.
440   inline const OpenGl_Clipping& Clipping() const { return myClippingState; }
441
442   //! @return tool for management of shader programs within this context.
443   inline const Handle(OpenGl_ShaderManager)& ShaderManager() const { return myShaderManager; }
444
445 public:
446
447   //! Either GL_CLAMP_TO_EDGE (1.2+) or GL_CLAMP (1.1).
448   Standard_Integer TextureWrapClamp() const { return myTexClamp; }
449
450   //! @return maximum degree of anisotropy texture filter
451   Standard_Integer MaxDegreeOfAnisotropy() const { return myAnisoMax; }
452
453   //! @return value for GL_MAX_TEXTURE_SIZE
454   Standard_Integer MaxTextureSize() const { return myMaxTexDim; }
455
456   //! @return value for GL_MAX_SAMPLES
457   Standard_Integer MaxMsaaSamples() const { return myMaxMsaaSamples; }
458
459   //! Get maximum number of clip planes supported by OpenGl.
460   //! This value is implementation dependent. At least 6
461   //! planes should be supported by OpenGl (see specs).
462   //! @return value for GL_MAX_CLIP_PLANES
463   Standard_Integer MaxClipPlanes() const { return myMaxClipPlanes; }
464
465   //! @return TRUE if ray tracing mode is supported
466   Standard_Boolean HasRayTracing() const { return myHasRayTracing; }
467
468   //! @return TRUE if textures in ray tracing mode are supported
469   Standard_Boolean HasRayTracingTextures() const { return myHasRayTracingTextures; }
470
471   //! @return TRUE if adaptive screen sampling in ray tracing mode is supported
472   Standard_Boolean HasRayTracingAdaptiveSampling() const { return myHasRayTracingAdaptiveSampling; }
473
474   //! Returns true if VBO is supported and permitted.
475   inline bool ToUseVbo() const
476   {
477     return core15fwd != NULL
478        && !caps->vboDisable;
479   }
480
481   //! @return cached state of GL_NORMALIZE.
482   Standard_Boolean IsGlNormalizeEnabled() const { return myIsGlNormalizeEnabled; }
483
484   //! Sets GL_NORMALIZE enabled or disabled.
485   //! @return old value of the flag
486   Standard_EXPORT Standard_Boolean SetGlNormalizeEnabled (Standard_Boolean isEnabled);
487
488   //! @return cached state of polygon rasterization mode (glPolygonMode()).
489   Standard_Integer PolygonMode() const { return myPolygonMode; }
490
491   //! Sets polygon rasterization mode (glPolygonMode() function).
492   //! @return old value of the rasterization mode.
493   Standard_EXPORT Standard_Integer SetPolygonMode (const Standard_Integer theMode);
494
495   //! @return cached enabled state of polygon hatching rasterization.
496   bool IsPolygonHatchEnabled() const
497   {
498     return !myHatchStyles.IsNull() && myHatchStyles->TypeOfHatch() != 0;
499   }
500
501   //! Sets enabled state of polygon hatching rasterization
502   //! without affecting currently selected hatching pattern.
503   //! @return previous state of polygon hatching mode.
504   Standard_EXPORT bool SetPolygonHatchEnabled (const bool theIsEnabled);
505
506   //! @return cached state of polygon hatch type.
507   Standard_Integer PolygonHatchStyle() const
508   {
509     return myHatchStyles.IsNull() ? Aspect_HS_SOLID : myHatchStyles->TypeOfHatch();
510   }
511
512   //! Sets polygon hatch pattern.
513   //! Zero-index value is a default alias for solid filling.
514   //! @param the type of hatch supported by base implementation of
515   //! OpenGl_LineAttributes (Aspect_HatchStyle) or the type supported by custom
516   //! implementation derived from OpenGl_LineAttributes class.
517   //! @return old type of hatch.
518   Standard_EXPORT Standard_Integer SetPolygonHatchStyle (const Handle(Graphic3d_HatchStyle)& theStyle);
519
520   //! Applies matrix stored in ModelWorldState to OpenGl.
521   Standard_EXPORT void ApplyModelWorldMatrix();
522
523   //! Applies matrix stored in WorldViewState to OpenGl.
524   Standard_EXPORT void ApplyWorldViewMatrix();
525
526   //! Applies combination of matrices stored in ModelWorldState and WorldViewState to OpenGl.
527   Standard_EXPORT void ApplyModelViewMatrix();
528
529   //! Applies matrix stored in ProjectionState to OpenGl.
530   Standard_EXPORT void ApplyProjectionMatrix();
531
532 public:
533
534   //! @return messenger instance
535   inline const Handle(Message_Messenger)& Messenger() const
536   {
537     return ::Message::DefaultMessenger();
538   }
539
540   //! Callback for GL_ARB_debug_output extension
541   //! @param theSource   message source   within GL_DEBUG_SOURCE_   enumeration
542   //! @param theType     message type     within GL_DEBUG_TYPE_     enumeration
543   //! @param theId       message ID       within source
544   //! @param theSeverity message severity within GL_DEBUG_SEVERITY_ enumeration
545   //! @param theMessage  the message itself
546   Standard_EXPORT void PushMessage (const unsigned int theSource,
547                                     const unsigned int theType,
548                                     const unsigned int theId,
549                                     const unsigned int theSeverity,
550                                     const TCollection_ExtendedString& theMessage);
551
552   //! Adds a filter for messages with theId and theSource (GL_DEBUG_SOURCE_)
553   Standard_EXPORT Standard_Boolean ExcludeMessage (const unsigned int theSource,
554                                                    const unsigned int theId);
555
556   //! Removes a filter for messages with theId and theSource (GL_DEBUG_SOURCE_)
557   Standard_EXPORT Standard_Boolean IncludeMessage (const unsigned int theSource,
558                                                    const unsigned int theId);
559
560   //! @return true if OpenGl context supports left and
561   //! right rendering buffers.
562   Standard_Boolean HasStereoBuffers() const
563   {
564   #if !defined(GL_ES_VERSION_2_0)
565     return myIsStereoBuffers;
566   #else
567     return Standard_False;
568   #endif
569   }
570
571 public: //! @name methods to alter or retrieve current state
572
573   //! Return cached viewport definition (x, y, width, height).
574   const Standard_Integer* Viewport() const { return myViewport; }
575
576   //! Resize the viewport (alias for glViewport).
577   //! @param theRect viewport definition (x, y, width, height)
578   Standard_EXPORT void ResizeViewport (const Standard_Integer theRect[4]);
579
580   //! Return active read buffer.
581   Standard_Integer ReadBuffer() { return myReadBuffer; }
582
583   //! Switch read buffer, wrapper for ::glReadBuffer().
584   Standard_EXPORT void SetReadBuffer (const Standard_Integer theReadBuffer);
585
586   //! Return active draw buffer.
587   Standard_Integer DrawBuffer() { return myDrawBuffer; }
588
589   //! Switch draw buffer, wrapper for ::glDrawBuffer().
590   Standard_EXPORT void SetDrawBuffer (const Standard_Integer theDrawBuffer);
591
592   //! Switch read/draw buffers.
593   void SetReadDrawBuffer (const Standard_Integer theBuffer)
594   {
595     SetReadBuffer (theBuffer);
596     SetDrawBuffer (theBuffer);
597   }
598
599   //! Return back face culling state.
600   bool ToCullBackFaces() const { return myToCullBackFaces; }
601
602   //! Enable or disable back face culling (glEnable (GL_CULL_FACE)).
603   Standard_EXPORT void SetCullBackFaces (bool theToEnable);
604
605   //! Fetch OpenGl context state. This class tracks value of several OpenGl
606   //! state variables. Consulting the cached values is quicker than
607   //! doing the same via OpenGl API. Call this method if any of the controlled
608   //! OpenGl state variables has a possibility of being out-of-date.
609   Standard_EXPORT void FetchState();
610
611   //! @return active GLSL program
612   const Handle(OpenGl_ShaderProgram)& ActiveProgram() const
613   {
614     return myActiveProgram;
615   }
616
617   //! @return OpenGL sampler object used to override default texture parameters
618   const Handle(OpenGl_Sampler)& TextureSampler()
619   {
620     return myTexSampler;
621   }
622
623   //! Bind specified program to current context,
624   //! or unbind previous one when NULL specified.
625   //! @return true if some program is bound to context
626   Standard_EXPORT Standard_Boolean BindProgram (const Handle(OpenGl_ShaderProgram)& theProgram);
627
628   //! Setup current shading material.
629   Standard_EXPORT void SetShadingMaterial (const OpenGl_AspectFace* theAspect,
630                                            const Handle(Graphic3d_PresentationAttributes)& theHighlight,
631                                            const Standard_Boolean theUseDepthWrite);
632
633   //! Setup current color.
634   Standard_EXPORT void SetColor4fv (const OpenGl_Vec4& theColor);
635
636   //! Setup type of line.
637   Standard_EXPORT void SetTypeOfLine (const Aspect_TypeOfLine  theType,
638                                       const Standard_ShortReal theFactor = 1.0f);
639
640   //! Setup width of line.
641   Standard_EXPORT void SetLineWidth (const Standard_ShortReal theWidth);
642
643   //! Setup point size.
644   Standard_EXPORT void SetPointSize (const Standard_ShortReal theSize);
645
646   //! Setup point sprite origin using GL_POINT_SPRITE_COORD_ORIGIN state:
647   //! - GL_UPPER_LEFT when GLSL program is active;
648   //!   flipping should be handled in GLSL program for compatibility with OpenGL ES
649   //! - GL_LOWER_LEFT for FFP
650   Standard_EXPORT void SetPointSpriteOrigin();
651
652   //! Setup texture matrix to active GLSL program or to FFP global state using glMatrixMode (GL_TEXTURE).
653   Standard_EXPORT void SetTextureMatrix (const Handle(Graphic3d_TextureParams)& theParams);
654
655   //! Bind default Vertex Array Object
656   Standard_EXPORT void BindDefaultVao();
657
658   //! Default Frame Buffer Object.
659   const Handle(OpenGl_FrameBuffer)& DefaultFrameBuffer() const
660   {
661     return myDefaultFbo;
662   }
663
664   //! Setup new Default Frame Buffer Object and return previously set.
665   //! This call doesn't change Active FBO!
666   Standard_EXPORT Handle(OpenGl_FrameBuffer) SetDefaultFrameBuffer (const Handle(OpenGl_FrameBuffer)& theFbo);
667
668   //! Return debug context initialization state.
669   Standard_Boolean IsDebugContext() const
670   {
671     return myIsGlDebugCtx;
672   }
673
674   Standard_EXPORT void EnableFeatures() const;
675
676   Standard_EXPORT void DisableFeatures() const;
677
678   //! Set resolution ratio.
679   //! Note that this method rounds @theRatio to nearest integer.
680   void SetResolutionRatio (const Standard_ShortReal theRatio)
681   {
682     myResolutionRatio = Max (1.0f, std::floor (theRatio + 0.5f));
683   }
684
685 private:
686
687   //! Wrapper to system function to retrieve GL function pointer by name.
688   Standard_EXPORT void* findProc (const char* theFuncName);
689
690   //! Print error if not all functions have been exported by context for reported version.
691   //! Note that this will never happen when using GLX, since returned functions can not be validated.
692   //! @param theGlVerMajor the OpenGL major version with missing functions
693   //! @param theGlVerMinor the OpenGL minor version with missing functions
694   Standard_EXPORT void checkWrongVersion (const Standard_Integer theGlVerMajor,
695                                           const Standard_Integer theGlVerMinor);
696
697   //! Private initialization function that should be called only once.
698   Standard_EXPORT void init (const Standard_Boolean theIsCoreProfile);
699
700 public: //! @name core profiles
701
702   OpenGl_GlCore11*     core11;     //!< OpenGL 1.1 core functionality
703   OpenGl_GlCore11Fwd*  core11fwd;  //!< OpenGL 1.1 without deprecated entry points
704   OpenGl_GlCore15*     core15;     //!< OpenGL 1.5 core functionality
705   OpenGl_GlCore15Fwd*  core15fwd;  //!< OpenGL 1.5 without deprecated entry points
706   OpenGl_GlCore20*     core20;     //!< OpenGL 2.0 core functionality (includes 1.5)
707   OpenGl_GlCore20Fwd*  core20fwd;  //!< OpenGL 2.0 without deprecated entry points
708   OpenGl_GlCore32*     core32;     //!< OpenGL 3.2 core profile
709   OpenGl_GlCore32Back* core32back; //!< OpenGL 3.2 backward compatibility profile
710   OpenGl_GlCore33*     core33;     //!< OpenGL 3.3 core profile
711   OpenGl_GlCore33Back* core33back; //!< OpenGL 3.3 backward compatibility profile
712   OpenGl_GlCore41*     core41;     //!< OpenGL 4.1 core profile
713   OpenGl_GlCore41Back* core41back; //!< OpenGL 4.1 backward compatibility profile
714   OpenGl_GlCore42*     core42;     //!< OpenGL 4.2 core profile
715   OpenGl_GlCore42Back* core42back; //!< OpenGL 4.2 backward compatibility profile
716   OpenGl_GlCore43*     core43;     //!< OpenGL 4.3 core profile
717   OpenGl_GlCore43Back* core43back; //!< OpenGL 4.3 backward compatibility profile
718   OpenGl_GlCore44*     core44;     //!< OpenGL 4.4 core profile
719   OpenGl_GlCore44Back* core44back; //!< OpenGL 4.4 backward compatibility profile
720
721   Handle(OpenGl_Caps) caps; //!< context options
722
723 public: //! @name extensions
724
725   Standard_Boolean       hasHighp;       //!< highp in GLSL ES fragment shader is supported
726   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)
727   Standard_Boolean       hasTexRGBA8;    //!< always available on desktop; on OpenGL ES - since 3.0 or as extension GL_OES_rgb8_rgba8
728   Standard_Boolean       arbNPTW;        //!< GL_ARB_texture_non_power_of_two
729   Standard_Boolean       arbTexRG;       //!< GL_ARB_texture_rg
730   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)
731   OpenGl_ArbTexBindless* arbTexBindless; //!< GL_ARB_bindless_texture
732   OpenGl_ArbTBO*         arbTBO;         //!< GL_ARB_texture_buffer_object
733   Standard_Boolean       arbTboRGB32;    //!< GL_ARB_texture_buffer_object_rgb32 (3-component TBO), in core since 4.0
734   OpenGl_ArbIns*         arbIns;         //!< GL_ARB_draw_instanced
735   OpenGl_ArbDbg*         arbDbg;         //!< GL_ARB_debug_output
736   OpenGl_ArbFBO*         arbFBO;         //!< GL_ARB_framebuffer_object
737   OpenGl_ArbFBOBlit*     arbFBOBlit;     //!< glBlitFramebuffer function, moved out from OpenGl_ArbFBO structure for compatibility with OpenGL ES 2.0
738   Standard_Boolean       extFragDepth;   //!< GL_EXT_frag_depth on OpenGL ES 2.0 (gl_FragDepthEXT built-in variable, before OpenGL ES 3.0)
739   OpenGl_ExtGS*          extGS;          //!< GL_EXT_geometry_shader4
740   Standard_Boolean       extBgra;        //!< GL_EXT_bgra or GL_EXT_texture_format_BGRA8888 on OpenGL ES
741   Standard_Boolean       extAnis;        //!< GL_EXT_texture_filter_anisotropic
742   Standard_Boolean       extPDS;         //!< GL_EXT_packed_depth_stencil
743   Standard_Boolean       atiMem;         //!< GL_ATI_meminfo
744   Standard_Boolean       nvxMem;         //!< GL_NVX_gpu_memory_info
745
746 public: //! @name public properties tracking current state
747
748   OpenGl_MatrixState<Standard_ShortReal> ModelWorldState; //!< state of orientation matrix
749   OpenGl_MatrixState<Standard_ShortReal> WorldViewState;  //!< state of orientation matrix
750   OpenGl_MatrixState<Standard_ShortReal> ProjectionState; //!< state of projection  matrix
751
752 private: // system-dependent fields
753
754 #if defined(HAVE_EGL)
755   Aspect_Drawable         myWindow;   //!< EGL surface                   : EGLSurface
756   Aspect_Display          myDisplay;  //!< EGL connection to the Display : EGLDisplay
757   Aspect_RenderingContext myGContext; //!< EGL rendering context         : EGLContext
758 #elif defined(_WIN32)
759   Aspect_Handle           myWindow;   //!< window handle (owner of GL context) : HWND
760   Aspect_Handle           myWindowDC; //!< Device Descriptor handle : HDC
761   Aspect_RenderingContext myGContext; //!< Rendering Context handle : HGLRC
762 #elif defined(__APPLE__) && !defined(MACOSX_USE_GLX)
763   #if defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE
764   EAGLContext*            myGContext;    //!< Rendering Context handle
765   #else
766   NSOpenGLContext*        myGContext; //!< Rendering Context handle
767   #endif
768 #else
769   Aspect_Drawable         myWindow;   //!< window handle (owner of GL context) : GLXDrawable
770   Aspect_Display          myDisplay;  //!< connection to the X-server : Display*
771   Aspect_RenderingContext myGContext; //!< X-GLX rendering context : GLXContext
772 #endif
773
774 private: // context info
775
776   typedef NCollection_Shared< NCollection_DataMap<TCollection_AsciiString, Standard_Integer> > OpenGl_DelayReleaseMap;
777   typedef NCollection_Shared< NCollection_DataMap<TCollection_AsciiString, Handle(OpenGl_Resource)> > OpenGl_ResourcesMap;
778   typedef NCollection_Shared< NCollection_List<Handle(OpenGl_Resource)> > OpenGl_ResourcesStack;
779
780   Handle(OpenGl_ResourcesMap)    mySharedResources; //!< shared resources with unique identification key
781   Handle(OpenGl_DelayReleaseMap) myDelayed;         //!< shared resources for delayed release
782   Handle(OpenGl_ResourcesStack)  myUnusedResources; //!< stack of resources for delayed clean up
783
784   OpenGl_Clipping myClippingState; //!< state of clip planes
785
786   void*            myGlLibHandle;          //!< optional handle to GL library
787   NCollection_Handle<OpenGl_GlFunctions>
788                    myFuncs;                //!< mega structure for all GL functions
789   Standard_Integer myAnisoMax;             //!< maximum level of anisotropy texture filter
790   Standard_Integer myTexClamp;             //!< either GL_CLAMP_TO_EDGE (1.2+) or GL_CLAMP (1.1)
791   Standard_Integer myMaxTexDim;            //!< value for GL_MAX_TEXTURE_SIZE
792   Standard_Integer myMaxClipPlanes;        //!< value for GL_MAX_CLIP_PLANES
793   Standard_Integer myMaxMsaaSamples;       //!< value for GL_MAX_SAMPLES
794   Standard_Integer myGlVerMajor;           //!< cached GL version major number
795   Standard_Integer myGlVerMinor;           //!< cached GL version minor number
796   Standard_Boolean myIsInitialized;        //!< flag indicates initialization state
797   Standard_Boolean myIsStereoBuffers;      //!< context supports stereo buffering
798   Standard_Boolean myIsGlNormalizeEnabled; //!< GL_NORMALIZE flag
799                                            //!< Used to tell OpenGl that normals should be normalized
800
801   Standard_Boolean myHasRayTracing;                 //! indicates whether ray tracing mode is supported 
802   Standard_Boolean myHasRayTracingTextures;         //! indicates whether textures in ray tracing mode are supported 
803   Standard_Boolean myHasRayTracingAdaptiveSampling; //! indicates whether adaptive screen sampling in ray tracing mode is supported 
804
805   Handle(OpenGl_ShaderManager) myShaderManager; //! support object for managing shader programs
806
807 private: //! @name fields tracking current state
808
809   Handle(OpenGl_ShaderProgram)  myActiveProgram;   //!< currently active GLSL program
810   Handle(OpenGl_Sampler)        myTexSampler;      //!< currently active sampler object
811   Handle(OpenGl_FrameBuffer)    myDefaultFbo;      //!< default Frame Buffer Object
812   Handle(OpenGl_LineAttributes) myHatchStyles;     //!< resource holding predefined hatch styles patterns
813   Standard_Integer              myViewport[4];     //!< current viewport
814   Standard_Integer              myPointSpriteOrig; //!< GL_POINT_SPRITE_COORD_ORIGIN state (GL_UPPER_LEFT by default)
815   Standard_Integer              myRenderMode;      //!< value for active rendering mode
816   Standard_Integer              myPolygonMode;     //!< currently used polygon rasterization mode (glPolygonMode)
817   bool                          myToCullBackFaces; //!< back face culling mode enabled state (glIsEnabled (GL_CULL_FACE))
818   Standard_Integer              myReadBuffer;      //!< current read buffer
819   Standard_Integer              myDrawBuffer;      //!< current draw buffer
820   unsigned int                  myDefaultVao;      //!< default Vertex Array Object
821   Standard_Boolean              myIsGlDebugCtx;    //!< debug context initialization state
822   TCollection_AsciiString       myVendor;          //!< Graphics Driver's vendor
823   TColStd_PackedMapOfInteger    myFilters[6];      //!< messages suppressing filter (for sources from GL_DEBUG_SOURCE_API_ARB to GL_DEBUG_SOURCE_OTHER_ARB)
824   Standard_ShortReal            myResolutionRatio; //!< scaling factor for parameters like text size
825                                                    //!< to be properly displayed on device (screen / printer)
826   OpenGl_Material               myMatFront;        //!< current front material state (cached to reduce GL context updates)
827   OpenGl_Material               myMatBack;         //!< current back  material state
828
829 private:
830
831   //! Copying allowed only within Handles
832   OpenGl_Context            (const OpenGl_Context& );
833   OpenGl_Context& operator= (const OpenGl_Context& );
834
835 };
836
837 #endif // _OpenGl_Context_H__