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