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