1 // Created on: 2012-01-26
2 // Created by: Kirill GAVRILOV
3 // Copyright (c) 2012-2014 OPEN CASCADE SAS
5 // This file is part of Open CASCADE Technology software library.
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.
13 // Alternatively, this file may be used under the terms of Open CASCADE
14 // commercial license or contractual agreement.
16 #ifndef _OpenGl_Context_H__
17 #define _OpenGl_Context_H__
19 #include <Aspect_Handle.hxx>
20 #include <Aspect_HatchStyle.hxx>
21 #include <Aspect_Drawable.hxx>
22 #include <Aspect_Display.hxx>
23 #include <Aspect_RenderingContext.hxx>
24 #include <Aspect_TypeOfLine.hxx>
25 #include <NCollection_DataMap.hxx>
26 #include <Graphic3d_DiagnosticInfo.hxx>
27 #include <Graphic3d_TextureUnit.hxx>
28 #include <NCollection_Map.hxx>
29 #include <NCollection_Handle.hxx>
30 #include <NCollection_List.hxx>
31 #include <NCollection_SparseArray.hxx>
32 #include <Message.hxx>
33 #include <OpenGl_Caps.hxx>
34 #include <OpenGl_LineAttributes.hxx>
35 #include <OpenGl_Material.hxx>
36 #include <OpenGl_MatrixState.hxx>
37 #include <OpenGl_Vec.hxx>
38 #include <OpenGl_Resource.hxx>
39 #include <OpenGl_TextureSet.hxx>
40 #include <Standard_Transient.hxx>
41 #include <TColStd_IndexedDataMapOfStringString.hxx>
42 #include <TColStd_PackedMapOfInteger.hxx>
43 #include <OpenGl_Clipping.hxx>
44 #include <OpenGl_GlCore11.hxx>
46 #include <NCollection_Shared.hxx>
48 //! Forward declarations
49 #if defined(__APPLE__)
50 #import <TargetConditionals.h>
51 #if defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE
59 @class NSOpenGLContext;
61 struct NSOpenGLContext;
66 struct OpenGl_GlFunctions;
71 struct OpenGl_ArbFBOBlit;
72 struct OpenGl_ArbSamplerObject;
73 struct OpenGl_ArbTexBindless;
76 template<typename theBaseClass_t> struct OpenGl_TmplCore12;
77 typedef OpenGl_TmplCore12<OpenGl_GlCore11> OpenGl_GlCore12;
78 typedef OpenGl_TmplCore12<OpenGl_GlCore11Fwd> OpenGl_GlCore12Fwd;
80 struct OpenGl_GlCore13;
81 struct OpenGl_GlCore13Fwd;
83 template<typename theBaseClass_t> struct OpenGl_TmplCore14;
84 typedef OpenGl_TmplCore14<OpenGl_GlCore13> OpenGl_GlCore14;
85 typedef OpenGl_TmplCore14<OpenGl_GlCore13Fwd> OpenGl_GlCore14Fwd;
87 template<typename theBaseClass_t> struct OpenGl_TmplCore15;
88 typedef OpenGl_TmplCore15<OpenGl_GlCore14> OpenGl_GlCore15;
89 typedef OpenGl_TmplCore15<OpenGl_GlCore14Fwd> OpenGl_GlCore15Fwd;
91 template<typename theBaseClass_t> struct OpenGl_TmplCore20;
92 typedef OpenGl_TmplCore20<OpenGl_GlCore15> OpenGl_GlCore20;
93 typedef OpenGl_TmplCore20<OpenGl_GlCore15Fwd> OpenGl_GlCore20Fwd;
95 template<typename theBaseClass_t> struct OpenGl_TmplCore21;
96 typedef OpenGl_TmplCore21<OpenGl_GlCore20> OpenGl_GlCore21;
97 typedef OpenGl_TmplCore21<OpenGl_GlCore20Fwd> OpenGl_GlCore21Fwd;
99 template<typename theBaseClass_t> struct OpenGl_TmplCore30;
100 typedef OpenGl_TmplCore30<OpenGl_GlCore21> OpenGl_GlCore30;
101 typedef OpenGl_TmplCore30<OpenGl_GlCore21Fwd> OpenGl_GlCore30Fwd;
103 template<typename theBaseClass_t> struct OpenGl_TmplCore31;
104 typedef OpenGl_TmplCore31<OpenGl_GlCore30> OpenGl_GlCore31Back;
105 typedef OpenGl_TmplCore31<OpenGl_GlCore30Fwd> OpenGl_GlCore31;
107 template<typename theBaseClass_t> struct OpenGl_TmplCore32;
108 typedef OpenGl_TmplCore32<OpenGl_GlCore31Back> OpenGl_GlCore32Back;
109 typedef OpenGl_TmplCore32<OpenGl_GlCore31> OpenGl_GlCore32;
111 template<typename theBaseClass_t> struct OpenGl_TmplCore33;
112 typedef OpenGl_TmplCore33<OpenGl_GlCore32Back> OpenGl_GlCore33Back;
113 typedef OpenGl_TmplCore33<OpenGl_GlCore32> OpenGl_GlCore33;
115 template<typename theBaseClass_t> struct OpenGl_TmplCore40;
116 typedef OpenGl_TmplCore40<OpenGl_GlCore33Back> OpenGl_GlCore40Back;
117 typedef OpenGl_TmplCore40<OpenGl_GlCore33> OpenGl_GlCore40;
119 template<typename theBaseClass_t> struct OpenGl_TmplCore41;
120 typedef OpenGl_TmplCore41<OpenGl_GlCore40Back> OpenGl_GlCore41Back;
121 typedef OpenGl_TmplCore41<OpenGl_GlCore40> OpenGl_GlCore41;
123 template<typename theBaseClass_t> struct OpenGl_TmplCore42;
124 typedef OpenGl_TmplCore42<OpenGl_GlCore41Back> OpenGl_GlCore42Back;
125 typedef OpenGl_TmplCore42<OpenGl_GlCore41> OpenGl_GlCore42;
127 template<typename theBaseClass_t> struct OpenGl_TmplCore43;
128 typedef OpenGl_TmplCore43<OpenGl_GlCore42Back> OpenGl_GlCore43Back;
129 typedef OpenGl_TmplCore43<OpenGl_GlCore42> OpenGl_GlCore43;
131 template<typename theBaseClass_t> struct OpenGl_TmplCore44;
132 typedef OpenGl_TmplCore44<OpenGl_GlCore43Back> OpenGl_GlCore44Back;
133 typedef OpenGl_TmplCore44<OpenGl_GlCore43> OpenGl_GlCore44;
135 class Graphic3d_PresentationAttributes;
136 class OpenGl_AspectFace;
137 class OpenGl_FrameBuffer;
138 class OpenGl_Sampler;
139 class OpenGl_ShaderProgram;
140 class OpenGl_ShaderManager;
142 enum OpenGl_FeatureFlag
144 OpenGl_FeatureNotAvailable = 0, //!< Feature is not supported by OpenGl implementation.
145 OpenGl_FeatureInExtensions = 1, //!< Feature is supported as extension.
146 OpenGl_FeatureInCore = 2 //!< Feature is supported as part of core profile.
149 DEFINE_STANDARD_HANDLE(OpenGl_Context, Standard_Transient)
151 //! This class generalize access to the GL context and available extensions.
153 //! Functions related to specific OpenGL version or extension are grouped into structures which can be accessed as fields of this class.
154 //! The most simple way to check that required functionality is available - is NULL check for the group:
156 //! if (myContext->core20 != NULL)
158 //! myGlProgram = myContext->core20->glCreateProgram();
159 //! .. do more stuff ..
163 //! .. compatibility with outdated configurations ..
167 //! Current implementation provide access to OpenGL core functionality up to 4.4 version (core12, core13, core14, core15, fields core20)
168 //! as well as several extensions (arbTBO, arbFBO, etc.).
170 //! OpenGL context might be initialized in Core Profile. In this case deprecated functionality become unavailable.
171 //! To make code easily adaptable to wide range of OpenGL versions, function sets related to each version has two kinds of suffixes:
172 //! - "back" for version 3.2+.
173 //! Represents function set for Backward-Compatible Profile.
174 //! Function sets without this suffix represents core profile.
175 //! - "fwd" for version 3.0-.
176 //! Represents non-deprecated function set of earlier OpenGL versions, which are still available within OpenGL 3.2 Core Profile.
177 //! Function sets without this suffix represents complete list of functions related to specific OpenGL version.
179 //! To select which core** function set should be used in specific case:
180 //! - Determine the minimal OpenGL version required for implemented functionality and use it to access all functions.
181 //! For example, if algorithm requires OpenGL 2.1+, it is better to write core20fwd->glEnable() rather than core11fwd->glEnable() for uniformity.
182 //! - If functionality will work within Core Profile, use function sets with appropriate suffix.
183 //! - Validate minimal requirements at initialization/creation time and omit checks within code where algorithm should be already initialized.
184 //! Properly escape code incompatible with Core Profile. The simplest way to check Core Profile is "if (core11 == NULL)".
186 //! Simplified extensions classification:
187 //! - prefixed with NV, AMD, ATI are vendor-specific (however may be provided by other vendors in some cases);
188 //! - prefixed with EXT are accepted by 2+ vendors;
189 //! - prefixed with ARB are accepted by Architecture Review Board and are candidates
190 //! for inclusion into GL core functionality.
191 //! Some functionality can be represented in several extensions simultaneously.
192 //! In this case developer should be careful because different specification may differ
193 //! in aspects (like enumeration values and error-handling).
195 //! Notice that some systems provide mechanisms to simultaneously incorporate with GL contexts with different capabilities.
196 //! For this reason OpenGl_Context should be initialized and used for each GL context independently.
197 class OpenGl_Context : public Standard_Transient
199 DEFINE_STANDARD_RTTIEXT(OpenGl_Context, Standard_Transient)
200 friend class OpenGl_Window;
203 //! Function for getting power of to number larger or equal to input number.
204 //! @param theNumber number to 'power of two'
205 //! @param theThreshold upper threshold
206 //! @return power of two number
207 inline static Standard_Integer GetPowerOfTwo (const Standard_Integer theNumber,
208 const Standard_Integer theThreshold)
210 for (Standard_Integer p2 = 2; p2 <= theThreshold; p2 <<= 1)
222 //! Empty constructor. You should call Init() to perform initialization with bound GL context.
223 Standard_EXPORT OpenGl_Context (const Handle(OpenGl_Caps)& theCaps = NULL);
226 Standard_EXPORT virtual ~OpenGl_Context();
228 //! Release all resources, including shared ones
229 Standard_EXPORT void forcedRelease();
231 //! Share GL context resources.
232 //! theShareCtx - handle to context to retrieve handles to shared resources.
233 Standard_EXPORT void Share (const Handle(OpenGl_Context)& theShareCtx);
235 //! Initialize class from currently bound OpenGL context. Method should be called only once.
236 //! @return false if no GL context is bound to the current thread
237 Standard_EXPORT Standard_Boolean Init (const Standard_Boolean theIsCoreProfile = Standard_False);
239 //! @return true if this context is valid (has been initialized)
240 inline Standard_Boolean IsValid() const
242 return myIsInitialized;
245 #if defined(HAVE_EGL)
246 //! Initialize class from specified surface and rendering context. Method should be called only once.
247 //! @return false if OpenGL context can not be bound to specified surface
248 Standard_EXPORT Standard_Boolean Init (const Aspect_Drawable theEglSurface,
249 const Aspect_Display theEglDisplay,
250 const Aspect_RenderingContext theEglContext,
251 const Standard_Boolean theIsCoreProfile = Standard_False);
252 #elif defined(_WIN32)
253 //! Initialize class from specified window and rendering context. Method should be called only once.
254 //! @return false if OpenGL context can not be bound to specified window
255 Standard_EXPORT Standard_Boolean Init (const Aspect_Handle theWindow,
256 const Aspect_Handle theWindowDC,
257 const Aspect_RenderingContext theGContext,
258 const Standard_Boolean theIsCoreProfile = Standard_False);
260 //! @return the window handle (HWND) currently bound to this OpenGL context
261 inline Aspect_Handle Window() const
266 #elif defined(__APPLE__) && !defined(MACOSX_USE_GLX)
267 #if defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE
269 //! Initialize class from specified OpenGL ES context (EAGLContext). Method should be called only once.
270 Standard_EXPORT Standard_Boolean Init (EAGLContext* theGContext,
271 const Standard_Boolean theIsCoreProfile = Standard_False);
274 //! Initialize class from specified OpenGL context (NSOpenGLContext). Method should be called only once.
275 Standard_EXPORT Standard_Boolean Init (NSOpenGLContext* theGContext,
276 const Standard_Boolean theIsCoreProfile = Standard_False);
280 //! Initialize class from specified window and rendering context. Method should be called only once.
281 //! @return false if OpenGL context can not be bound to specified window
282 Standard_EXPORT Standard_Boolean Init (const Aspect_Drawable theWindow,
283 const Aspect_Display theDisplay,
284 const Aspect_RenderingContext theGContext,
285 const Standard_Boolean theIsCoreProfile = Standard_False);
287 //! @return the window handle (GLXDrawable) currently bound to this OpenGL context
288 inline Aspect_Drawable Window() const
294 //! Read OpenGL version information from active context.
295 Standard_EXPORT static void ReadGlVersion (Standard_Integer& theGlVerMajor,
296 Standard_Integer& theGlVerMinor);
298 //! Check if theExtName extension is supported by active GL context.
299 Standard_EXPORT Standard_Boolean CheckExtension (const char* theExtName) const;
301 //! Check if theExtName extension is in extensions string.
302 Standard_EXPORT static Standard_Boolean CheckExtension (const char* theExtString,
303 const char* theExtName);
305 //! Auxiliary template to retrieve GL function pointer.
306 //! Pointer to function retrieved from library is statically casted
307 //! to requested type - there no way to check real signature of exported function.
308 //! The context should be bound before call.
309 template <typename FuncType_t>
310 Standard_Boolean FindProc (const char* theFuncName,
311 FuncType_t& theFuncPtr)
313 theFuncPtr = (FuncType_t )findProc (theFuncName);
314 return (theFuncPtr != NULL);
317 //! @return true if detected GL version is greater or equal to requested one.
318 inline Standard_Boolean IsGlGreaterEqual (const Standard_Integer theVerMajor,
319 const Standard_Integer theVerMinor) const
321 return (myGlVerMajor > theVerMajor)
322 || (myGlVerMajor == theVerMajor && myGlVerMinor >= theVerMinor);
325 //! Return cached GL version major number.
326 Standard_Integer VersionMajor() const { return myGlVerMajor; }
328 //! Return cached GL version minor number.
329 Standard_Integer VersionMinor() const { return myGlVerMinor; }
331 //! Access entire map of loaded OpenGL functions.
332 const OpenGl_GlFunctions* Functions() const { return myFuncs.operator->(); }
334 //! Clean up errors stack for this GL context (glGetError() in loop).
335 //! @return true if some error has been cleared
336 Standard_EXPORT bool ResetErrors (const bool theToPrintErrors = false);
338 //! This method uses system-dependent API to retrieve information
339 //! about GL context bound to the current thread.
340 //! @return true if current thread is bound to this GL context
341 Standard_EXPORT Standard_Boolean IsCurrent() const;
343 //! Activates current context.
344 //! Class should be initialized with appropriate info.
345 Standard_EXPORT Standard_Boolean MakeCurrent();
347 //! Swap front/back buffers for this GL context (should be activated before!).
348 Standard_EXPORT void SwapBuffers();
350 //! Setup swap interval (VSync).
351 Standard_EXPORT Standard_Boolean SetSwapInterval (const Standard_Integer theInterval);
353 //! Return true if active mode is GL_RENDER (cached state)
354 Standard_Boolean IsRender() const
356 #if !defined(GL_ES_VERSION_2_0)
357 return myRenderMode == GL_RENDER;
359 return Standard_True;
363 //! Return true if active mode is GL_FEEDBACK (cached state)
364 Standard_Boolean IsFeedback() const
366 #if !defined(GL_ES_VERSION_2_0)
367 return myRenderMode == GL_FEEDBACK;
369 return Standard_False;
373 //! This function retrieves information from GL about free GPU memory that is:
374 //! - OS-dependent. On some OS it is per-process and on others - for entire system.
375 //! - Vendor-dependent. Currently available only on NVIDIA and AMD/ATi drivers only.
376 //! - Numbers meaning may vary.
377 //! You should use this info only for diagnostics purposes.
378 //! @return free GPU dedicated memory in bytes.
379 Standard_EXPORT Standard_Size AvailableMemory() const;
381 //! This function retrieves information from GL about GPU memory
382 //! and contains more vendor-specific values than AvailableMemory().
383 Standard_EXPORT TCollection_AsciiString MemoryInfo() const;
385 //! This function retrieves information from GL about GPU memory.
386 Standard_EXPORT void MemoryInfo (TColStd_IndexedDataMapOfStringString& theDict) const;
388 //! Fill in the dictionary with OpenGL info.
389 //! Should be called with bound context.
390 Standard_EXPORT void DiagnosticInformation (TColStd_IndexedDataMapOfStringString& theDict,
391 Graphic3d_DiagnosticInfo theFlags) const;
393 //! Access shared resource by its name.
394 //! @param theKey - unique identifier;
395 //! @return handle to shared resource or NULL.
396 Standard_EXPORT const Handle(OpenGl_Resource)& GetResource (const TCollection_AsciiString& theKey) const;
398 //! Access shared resource by its name.
399 //! @param theKey - unique identifier;
400 //! @param theValue - handle to fill;
401 //! @return true if resource was shared.
402 template<typename TheHandleType>
403 Standard_Boolean GetResource (const TCollection_AsciiString& theKey,
404 TheHandleType& theValue) const
406 const Handle(OpenGl_Resource)& aResource = GetResource (theKey);
407 if (aResource.IsNull())
409 return Standard_False;
412 theValue = TheHandleType::DownCast (aResource);
413 return !theValue.IsNull();
416 //! Register shared resource.
417 //! Notice that after registration caller shouldn't release it by himself -
418 //! it will be automatically released on context destruction.
419 //! @param theKey - unique identifier, shouldn't be empty;
420 //! @param theResource - new resource to register, shouldn't be NULL.
421 Standard_EXPORT Standard_Boolean ShareResource (const TCollection_AsciiString& theKey,
422 const Handle(OpenGl_Resource)& theResource);
424 //! Release shared resource.
425 //! If there are more than one reference to this resource
426 //! (also used by some other existing object) then call will be ignored.
427 //! This means that current object itself should nullify handle before this call.
428 //! Notice that this is unrecommended operation at all and should be used
429 //! only in case of fat resources to release memory for other needs.
430 //! @param theKey unique identifier
431 //! @param theToDelay postpone release until next redraw call
432 Standard_EXPORT void ReleaseResource (const TCollection_AsciiString& theKey,
433 const Standard_Boolean theToDelay = Standard_False);
435 //! Append resource to queue for delayed clean up.
436 //! Resources in this queue will be released at next redraw call.
438 void DelayedRelease (Handle(T)& theResource)
440 myUnusedResources->Prepend (theResource);
441 theResource.Nullify();
444 //! Clean up the delayed release queue.
445 Standard_EXPORT void ReleaseDelayed();
447 //! @return tool for management of clippings within this context.
448 inline OpenGl_Clipping& ChangeClipping() { return myClippingState; }
450 //! @return tool for management of clippings within this context.
451 inline const OpenGl_Clipping& Clipping() const { return myClippingState; }
453 //! @return tool for management of shader programs within this context.
454 inline const Handle(OpenGl_ShaderManager)& ShaderManager() const { return myShaderManager; }
458 //! Either GL_CLAMP_TO_EDGE (1.2+) or GL_CLAMP (1.1).
459 Standard_Integer TextureWrapClamp() const { return myTexClamp; }
461 //! @return maximum degree of anisotropy texture filter
462 Standard_Integer MaxDegreeOfAnisotropy() const { return myAnisoMax; }
464 //! @return value for GL_MAX_TEXTURE_SIZE
465 Standard_Integer MaxTextureSize() const { return myMaxTexDim; }
467 //! @return value for GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS
468 Standard_Integer MaxCombinedTextureUnits() const { return myMaxTexCombined; }
470 //! @return value for GL_MAX_SAMPLES
471 Standard_Integer MaxMsaaSamples() const { return myMaxMsaaSamples; }
473 //! @return value for GL_MAX_DRAW_BUFFERS
474 Standard_Integer MaxDrawBuffers() const { return myMaxDrawBuffers; }
476 //! @return value for GL_MAX_COLOR_ATTACHMENTS
477 Standard_Integer MaxColorAttachments() const { return myMaxColorAttachments; }
479 //! Get maximum number of clip planes supported by OpenGl.
480 //! This value is implementation dependent. At least 6
481 //! planes should be supported by OpenGl (see specs).
482 //! @return value for GL_MAX_CLIP_PLANES
483 Standard_Integer MaxClipPlanes() const { return myMaxClipPlanes; }
485 //! @return TRUE if ray tracing mode is supported
486 Standard_Boolean HasRayTracing() const { return myHasRayTracing; }
488 //! @return TRUE if textures in ray tracing mode are supported
489 Standard_Boolean HasRayTracingTextures() const { return myHasRayTracingTextures; }
491 //! @return TRUE if adaptive screen sampling in ray tracing mode is supported
492 Standard_Boolean HasRayTracingAdaptiveSampling() const { return myHasRayTracingAdaptiveSampling; }
494 //! Returns true if VBO is supported and permitted.
495 inline bool ToUseVbo() const
497 return core15fwd != NULL
498 && !caps->vboDisable;
501 //! @return cached state of GL_NORMALIZE.
502 Standard_Boolean IsGlNormalizeEnabled() const { return myIsGlNormalizeEnabled; }
504 //! Sets GL_NORMALIZE enabled or disabled.
505 //! @return old value of the flag
506 Standard_EXPORT Standard_Boolean SetGlNormalizeEnabled (Standard_Boolean isEnabled);
508 //! @return cached state of polygon rasterization mode (glPolygonMode()).
509 Standard_Integer PolygonMode() const { return myPolygonMode; }
511 //! Sets polygon rasterization mode (glPolygonMode() function).
512 //! @return old value of the rasterization mode.
513 Standard_EXPORT Standard_Integer SetPolygonMode (const Standard_Integer theMode);
515 //! @return cached enabled state of polygon hatching rasterization.
516 bool IsPolygonHatchEnabled() const
518 return !myHatchStyles.IsNull() && myHatchStyles->TypeOfHatch() != 0;
521 //! Sets enabled state of polygon hatching rasterization
522 //! without affecting currently selected hatching pattern.
523 //! @return previous state of polygon hatching mode.
524 Standard_EXPORT bool SetPolygonHatchEnabled (const bool theIsEnabled);
526 //! @return cached state of polygon hatch type.
527 Standard_Integer PolygonHatchStyle() const
529 return myHatchStyles.IsNull() ? Aspect_HS_SOLID : myHatchStyles->TypeOfHatch();
532 //! Sets polygon hatch pattern.
533 //! Zero-index value is a default alias for solid filling.
534 //! @param the type of hatch supported by base implementation of
535 //! OpenGl_LineAttributes (Aspect_HatchStyle) or the type supported by custom
536 //! implementation derived from OpenGl_LineAttributes class.
537 //! @return old type of hatch.
538 Standard_EXPORT Standard_Integer SetPolygonHatchStyle (const Handle(Graphic3d_HatchStyle)& theStyle);
540 //! Applies matrix stored in ModelWorldState to OpenGl.
541 Standard_EXPORT void ApplyModelWorldMatrix();
543 //! Applies matrix stored in WorldViewState to OpenGl.
544 Standard_EXPORT void ApplyWorldViewMatrix();
546 //! Applies combination of matrices stored in ModelWorldState and WorldViewState to OpenGl.
547 Standard_EXPORT void ApplyModelViewMatrix();
549 //! Applies matrix stored in ProjectionState to OpenGl.
550 Standard_EXPORT void ApplyProjectionMatrix();
554 //! @return messenger instance
555 inline const Handle(Message_Messenger)& Messenger() const
557 return ::Message::DefaultMessenger();
560 //! Callback for GL_ARB_debug_output extension
561 //! @param theSource message source within GL_DEBUG_SOURCE_ enumeration
562 //! @param theType message type within GL_DEBUG_TYPE_ enumeration
563 //! @param theId message ID within source
564 //! @param theSeverity message severity within GL_DEBUG_SEVERITY_ enumeration
565 //! @param theMessage the message itself
566 Standard_EXPORT void PushMessage (const unsigned int theSource,
567 const unsigned int theType,
568 const unsigned int theId,
569 const unsigned int theSeverity,
570 const TCollection_ExtendedString& theMessage);
572 //! Adds a filter for messages with theId and theSource (GL_DEBUG_SOURCE_)
573 Standard_EXPORT Standard_Boolean ExcludeMessage (const unsigned int theSource,
574 const unsigned int theId);
576 //! Removes a filter for messages with theId and theSource (GL_DEBUG_SOURCE_)
577 Standard_EXPORT Standard_Boolean IncludeMessage (const unsigned int theSource,
578 const unsigned int theId);
580 //! @return true if OpenGl context supports left and
581 //! right rendering buffers.
582 Standard_Boolean HasStereoBuffers() const
584 #if !defined(GL_ES_VERSION_2_0)
585 return myIsStereoBuffers;
587 return Standard_False;
591 public: //! @name methods to alter or retrieve current state
593 //! Return cached viewport definition (x, y, width, height).
594 const Standard_Integer* Viewport() const { return myViewport; }
596 //! Resize the viewport (alias for glViewport).
597 //! @param theRect viewport definition (x, y, width, height)
598 Standard_EXPORT void ResizeViewport (const Standard_Integer theRect[4]);
600 //! Return virtual viewport definition (x, y, width, height).
601 const Standard_Integer* VirtualViewport() const { return myViewportVirt; }
603 //! Return active read buffer.
604 Standard_Integer ReadBuffer() { return myReadBuffer; }
606 //! Switch read buffer, wrapper for ::glReadBuffer().
607 Standard_EXPORT void SetReadBuffer (const Standard_Integer theReadBuffer);
609 //! Return active draw buffer attached to a render target referred by index (layout location).
610 Standard_Integer DrawBuffer (const Standard_Integer theIndex = 0)
612 return myDrawBuffers.IsBound (theIndex) ? myDrawBuffers.Value (theIndex) : GL_NONE;
615 //! Switch draw buffer, wrapper for ::glDrawBuffer().
616 Standard_EXPORT void SetDrawBuffer (const Standard_Integer theDrawBuffer);
618 //! Switch draw buffer, wrapper for ::glDrawBuffers (GLsizei, const GLenum*).
619 Standard_EXPORT void SetDrawBuffers (const Standard_Integer theNb, const Standard_Integer* theDrawBuffers);
621 //! Switch read/draw buffers.
622 void SetReadDrawBuffer (const Standard_Integer theBuffer)
624 SetReadBuffer (theBuffer);
625 SetDrawBuffer (theBuffer);
628 //! Return back face culling state.
629 bool ToCullBackFaces() const { return myToCullBackFaces; }
631 //! Enable or disable back face culling (glEnable (GL_CULL_FACE)).
632 Standard_EXPORT void SetCullBackFaces (bool theToEnable);
634 //! Fetch OpenGl context state. This class tracks value of several OpenGl
635 //! state variables. Consulting the cached values is quicker than
636 //! doing the same via OpenGl API. Call this method if any of the controlled
637 //! OpenGl state variables has a possibility of being out-of-date.
638 Standard_EXPORT void FetchState();
640 //! @return active textures
641 const Handle(OpenGl_TextureSet)& ActiveTextures() const { return myActiveTextures; }
643 //! Bind specified texture set to current context,
644 //! or unbind previous one when NULL specified.
645 Standard_EXPORT Handle(OpenGl_TextureSet) BindTextures (const Handle(OpenGl_TextureSet)& theTextures);
647 //! @return active GLSL program
648 const Handle(OpenGl_ShaderProgram)& ActiveProgram() const
650 return myActiveProgram;
653 //! Bind specified program to current context,
654 //! or unbind previous one when NULL specified.
655 //! @return true if some program is bound to context
656 Standard_EXPORT Standard_Boolean BindProgram (const Handle(OpenGl_ShaderProgram)& theProgram);
658 //! Setup current shading material.
659 Standard_EXPORT void SetShadingMaterial (const OpenGl_AspectFace* theAspect,
660 const Handle(Graphic3d_PresentationAttributes)& theHighlight);
662 //! Checks if transparency is required for the given aspect and highlight style.
663 Standard_EXPORT static Standard_Boolean CheckIsTransparent (const OpenGl_AspectFace* theAspect,
664 const Handle(Graphic3d_PresentationAttributes)& theHighlight,
665 Standard_ShortReal& theAlphaFront,
666 Standard_ShortReal& theAlphaBack);
668 //! Checks if transparency is required for the given aspect and highlight style.
669 static Standard_Boolean CheckIsTransparent (const OpenGl_AspectFace* theAspect,
670 const Handle(Graphic3d_PresentationAttributes)& theHighlight)
672 Standard_ShortReal anAlphaFront = 1.0f, anAlphaBack = 1.0f;
673 return CheckIsTransparent (theAspect, theHighlight, anAlphaFront, anAlphaBack);
676 //! Setup current color.
677 Standard_EXPORT void SetColor4fv (const OpenGl_Vec4& theColor);
679 //! Setup type of line.
680 Standard_EXPORT void SetTypeOfLine (const Aspect_TypeOfLine theType,
681 const Standard_ShortReal theFactor = 1.0f);
683 //! Setup width of line.
684 Standard_EXPORT void SetLineWidth (const Standard_ShortReal theWidth);
686 //! Setup point size.
687 Standard_EXPORT void SetPointSize (const Standard_ShortReal theSize);
689 //! Setup point sprite origin using GL_POINT_SPRITE_COORD_ORIGIN state:
690 //! - GL_UPPER_LEFT when GLSL program is active;
691 //! flipping should be handled in GLSL program for compatibility with OpenGL ES
692 //! - GL_LOWER_LEFT for FFP
693 Standard_EXPORT void SetPointSpriteOrigin();
695 //! Setup texture matrix to active GLSL program or to FFP global state using glMatrixMode (GL_TEXTURE).
696 Standard_EXPORT void SetTextureMatrix (const Handle(Graphic3d_TextureParams)& theParams);
698 //! Bind default Vertex Array Object
699 Standard_EXPORT void BindDefaultVao();
701 //! Default Frame Buffer Object.
702 const Handle(OpenGl_FrameBuffer)& DefaultFrameBuffer() const
707 //! Setup new Default Frame Buffer Object and return previously set.
708 //! This call doesn't change Active FBO!
709 Standard_EXPORT Handle(OpenGl_FrameBuffer) SetDefaultFrameBuffer (const Handle(OpenGl_FrameBuffer)& theFbo);
711 //! Return debug context initialization state.
712 Standard_Boolean IsDebugContext() const
714 return myIsGlDebugCtx;
717 Standard_EXPORT void EnableFeatures() const;
719 Standard_EXPORT void DisableFeatures() const;
721 //! Return resolution for rendering text.
722 unsigned int Resolution() const { return myResolution; }
724 //! Resolution scale factor (rendered resolution to standard resolution).
725 //! This scaling factor for parameters like text size to be properly displayed on device (screen / printer).
726 Standard_ShortReal ResolutionRatio() const { return myResolutionRatio; }
728 //! Rendering scale factor (rendering viewport height to real window buffer height).
729 Standard_ShortReal RenderScale() const { return myRenderScale; }
731 //! Return TRUE if rendering scale factor is not 1.
732 Standard_Boolean HasRenderScale() const { return Abs (myRenderScale - 1.0f) > 0.0001f; }
734 //! Rendering scale factor (inverted value).
735 Standard_ShortReal RenderScaleInv() const { return myRenderScaleInv; }
737 //! Set resolution ratio.
738 //! Note that this method rounds @theRatio to nearest integer.
739 void SetResolution (unsigned int theResolution,
740 Standard_ShortReal theRatio,
741 Standard_ShortReal theScale)
743 myResolution = (unsigned int )(theScale * theResolution + 0.5f);
744 myRenderScale = theScale;
745 myRenderScaleInv = 1.0f / theScale;
746 SetResolutionRatio (theRatio * theScale);
749 //! Set resolution ratio.
750 //! Note that this method rounds @theRatio to nearest integer.
751 void SetResolutionRatio (const Standard_ShortReal theRatio)
753 myResolutionRatio = theRatio;
754 myLineWidthScale = Max (1.0f, std::floor (theRatio + 0.5f));
759 //! Wrapper to system function to retrieve GL function pointer by name.
760 Standard_EXPORT void* findProc (const char* theFuncName);
762 //! Print error if not all functions have been exported by context for reported version.
763 //! Note that this will never happen when using GLX, since returned functions can not be validated.
764 //! @param theGlVerMajor the OpenGL major version with missing functions
765 //! @param theGlVerMinor the OpenGL minor version with missing functions
766 Standard_EXPORT void checkWrongVersion (const Standard_Integer theGlVerMajor,
767 const Standard_Integer theGlVerMinor);
769 //! Private initialization function that should be called only once.
770 Standard_EXPORT void init (const Standard_Boolean theIsCoreProfile);
772 public: //! @name core profiles
774 OpenGl_GlCore11* core11; //!< OpenGL 1.1 core functionality
775 OpenGl_GlCore11Fwd* core11fwd; //!< OpenGL 1.1 without deprecated entry points
776 OpenGl_GlCore15* core15; //!< OpenGL 1.5 core functionality
777 OpenGl_GlCore15Fwd* core15fwd; //!< OpenGL 1.5 without deprecated entry points
778 OpenGl_GlCore20* core20; //!< OpenGL 2.0 core functionality (includes 1.5)
779 OpenGl_GlCore20Fwd* core20fwd; //!< OpenGL 2.0 without deprecated entry points
780 OpenGl_GlCore32* core32; //!< OpenGL 3.2 core profile
781 OpenGl_GlCore32Back* core32back; //!< OpenGL 3.2 backward compatibility profile
782 OpenGl_GlCore33* core33; //!< OpenGL 3.3 core profile
783 OpenGl_GlCore33Back* core33back; //!< OpenGL 3.3 backward compatibility profile
784 OpenGl_GlCore41* core41; //!< OpenGL 4.1 core profile
785 OpenGl_GlCore41Back* core41back; //!< OpenGL 4.1 backward compatibility profile
786 OpenGl_GlCore42* core42; //!< OpenGL 4.2 core profile
787 OpenGl_GlCore42Back* core42back; //!< OpenGL 4.2 backward compatibility profile
788 OpenGl_GlCore43* core43; //!< OpenGL 4.3 core profile
789 OpenGl_GlCore43Back* core43back; //!< OpenGL 4.3 backward compatibility profile
790 OpenGl_GlCore44* core44; //!< OpenGL 4.4 core profile
791 OpenGl_GlCore44Back* core44back; //!< OpenGL 4.4 backward compatibility profile
793 Handle(OpenGl_Caps) caps; //!< context options
795 public: //! @name extensions
797 Standard_Boolean hasHighp; //!< highp in GLSL ES fragment shader is supported
798 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)
799 Standard_Boolean hasTexRGBA8; //!< always available on desktop; on OpenGL ES - since 3.0 or as extension GL_OES_rgb8_rgba8
800 OpenGl_FeatureFlag hasDrawBuffers; //!< Complex flag indicating support of multiple draw buffers (desktop OpenGL 2.0, OpenGL ES 3.0, GL_ARB_draw_buffers, GL_EXT_draw_buffers)
801 OpenGl_FeatureFlag hasFloatBuffer; //!< Complex flag indicating support of float color buffer format (desktop OpenGL 3.0, GL_ARB_color_buffer_float, GL_EXT_color_buffer_float)
802 OpenGl_FeatureFlag hasHalfFloatBuffer; //!< Complex flag indicating support of half-float color buffer format (desktop OpenGL 3.0, GL_ARB_color_buffer_float, GL_EXT_color_buffer_half_float)
803 OpenGl_FeatureFlag hasSampleVariables; //!< Complex flag indicating support of MSAA variables in GLSL shader (desktop OpenGL 4.0, GL_ARB_sample_shading)
804 Standard_Boolean arbDrawBuffers; //!< GL_ARB_draw_buffers
805 Standard_Boolean arbNPTW; //!< GL_ARB_texture_non_power_of_two
806 Standard_Boolean arbTexRG; //!< GL_ARB_texture_rg
807 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)
808 OpenGl_ArbSamplerObject* arbSamplerObject; //!< GL_ARB_sampler_objects (on desktop OpenGL - since 3.3 or as extension GL_ARB_sampler_objects; on OpenGL ES - since 3.0)
809 OpenGl_ArbTexBindless* arbTexBindless; //!< GL_ARB_bindless_texture
810 OpenGl_ArbTBO* arbTBO; //!< GL_ARB_texture_buffer_object
811 Standard_Boolean arbTboRGB32; //!< GL_ARB_texture_buffer_object_rgb32 (3-component TBO), in core since 4.0
812 OpenGl_ArbIns* arbIns; //!< GL_ARB_draw_instanced
813 OpenGl_ArbDbg* arbDbg; //!< GL_ARB_debug_output
814 OpenGl_ArbFBO* arbFBO; //!< GL_ARB_framebuffer_object
815 OpenGl_ArbFBOBlit* arbFBOBlit; //!< glBlitFramebuffer function, moved out from OpenGl_ArbFBO structure for compatibility with OpenGL ES 2.0
816 Standard_Boolean arbSampleShading; //!< GL_ARB_sample_shading
817 Standard_Boolean extFragDepth; //!< GL_EXT_frag_depth on OpenGL ES 2.0 (gl_FragDepthEXT built-in variable, before OpenGL ES 3.0)
818 Standard_Boolean extDrawBuffers; //!< GL_EXT_draw_buffers
819 OpenGl_ExtGS* extGS; //!< GL_EXT_geometry_shader4
820 Standard_Boolean extBgra; //!< GL_EXT_bgra or GL_EXT_texture_format_BGRA8888 on OpenGL ES
821 Standard_Boolean extAnis; //!< GL_EXT_texture_filter_anisotropic
822 Standard_Boolean extPDS; //!< GL_EXT_packed_depth_stencil
823 Standard_Boolean atiMem; //!< GL_ATI_meminfo
824 Standard_Boolean nvxMem; //!< GL_NVX_gpu_memory_info
825 Standard_Boolean oesSampleVariables; //!< GL_OES_sample_variables
827 public: //! @name public properties tracking current state
829 OpenGl_MatrixState<Standard_ShortReal> ModelWorldState; //!< state of orientation matrix
830 OpenGl_MatrixState<Standard_ShortReal> WorldViewState; //!< state of orientation matrix
831 OpenGl_MatrixState<Standard_ShortReal> ProjectionState; //!< state of projection matrix
833 private: // system-dependent fields
835 #if defined(HAVE_EGL)
836 Aspect_Drawable myWindow; //!< EGL surface : EGLSurface
837 Aspect_Display myDisplay; //!< EGL connection to the Display : EGLDisplay
838 Aspect_RenderingContext myGContext; //!< EGL rendering context : EGLContext
839 #elif defined(_WIN32)
840 Aspect_Handle myWindow; //!< window handle (owner of GL context) : HWND
841 Aspect_Handle myWindowDC; //!< Device Descriptor handle : HDC
842 Aspect_RenderingContext myGContext; //!< Rendering Context handle : HGLRC
843 #elif defined(__APPLE__) && !defined(MACOSX_USE_GLX)
844 #if defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE
845 EAGLContext* myGContext; //!< Rendering Context handle
847 NSOpenGLContext* myGContext; //!< Rendering Context handle
850 Aspect_Drawable myWindow; //!< window handle (owner of GL context) : GLXDrawable
851 Aspect_Display myDisplay; //!< connection to the X-server : Display*
852 Aspect_RenderingContext myGContext; //!< X-GLX rendering context : GLXContext
855 private: // context info
857 typedef NCollection_Shared< NCollection_DataMap<TCollection_AsciiString, Standard_Integer> > OpenGl_DelayReleaseMap;
858 typedef NCollection_Shared< NCollection_DataMap<TCollection_AsciiString, Handle(OpenGl_Resource)> > OpenGl_ResourcesMap;
859 typedef NCollection_Shared< NCollection_List<Handle(OpenGl_Resource)> > OpenGl_ResourcesStack;
860 typedef NCollection_SparseArray<Standard_Integer> OpenGl_DrawBuffers;
862 Handle(OpenGl_ResourcesMap) mySharedResources; //!< shared resources with unique identification key
863 Handle(OpenGl_DelayReleaseMap) myDelayed; //!< shared resources for delayed release
864 Handle(OpenGl_ResourcesStack) myUnusedResources; //!< stack of resources for delayed clean up
866 OpenGl_Clipping myClippingState; //!< state of clip planes
868 void* myGlLibHandle; //!< optional handle to GL library
869 NCollection_Handle<OpenGl_GlFunctions>
870 myFuncs; //!< mega structure for all GL functions
871 Standard_Integer myAnisoMax; //!< maximum level of anisotropy texture filter
872 Standard_Integer myTexClamp; //!< either GL_CLAMP_TO_EDGE (1.2+) or GL_CLAMP (1.1)
873 Standard_Integer myMaxTexDim; //!< value for GL_MAX_TEXTURE_SIZE
874 Standard_Integer myMaxTexCombined; //!< value for GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS
875 Standard_Integer myMaxClipPlanes; //!< value for GL_MAX_CLIP_PLANES
876 Standard_Integer myMaxMsaaSamples; //!< value for GL_MAX_SAMPLES
877 Standard_Integer myMaxDrawBuffers; //!< value for GL_MAX_DRAW_BUFFERS
878 Standard_Integer myMaxColorAttachments; //!< value for GL_MAX_COLOR_ATTACHMENTS
879 Standard_Integer myGlVerMajor; //!< cached GL version major number
880 Standard_Integer myGlVerMinor; //!< cached GL version minor number
881 Standard_Boolean myIsInitialized; //!< flag indicates initialization state
882 Standard_Boolean myIsStereoBuffers; //!< context supports stereo buffering
883 Standard_Boolean myIsGlNormalizeEnabled; //!< GL_NORMALIZE flag
884 //!< Used to tell OpenGl that normals should be normalized
886 Standard_Boolean myHasRayTracing; //! indicates whether ray tracing mode is supported
887 Standard_Boolean myHasRayTracingTextures; //! indicates whether textures in ray tracing mode are supported
888 Standard_Boolean myHasRayTracingAdaptiveSampling; //! indicates whether adaptive screen sampling in ray tracing mode is supported
890 Handle(OpenGl_ShaderManager) myShaderManager; //! support object for managing shader programs
892 private: //! @name fields tracking current state
894 Handle(OpenGl_ShaderProgram) myActiveProgram; //!< currently active GLSL program
895 Handle(OpenGl_TextureSet) myActiveTextures; //!< currently bound textures
896 //!< currently active sampler objects
897 Handle(OpenGl_FrameBuffer) myDefaultFbo; //!< default Frame Buffer Object
898 Handle(OpenGl_LineAttributes) myHatchStyles; //!< resource holding predefined hatch styles patterns
899 Standard_Integer myViewport[4]; //!< current viewport
900 Standard_Integer myViewportVirt[4]; //!< virtual viewport
901 Standard_Integer myPointSpriteOrig; //!< GL_POINT_SPRITE_COORD_ORIGIN state (GL_UPPER_LEFT by default)
902 Standard_Integer myRenderMode; //!< value for active rendering mode
903 Standard_Integer myPolygonMode; //!< currently used polygon rasterization mode (glPolygonMode)
904 bool myToCullBackFaces; //!< back face culling mode enabled state (glIsEnabled (GL_CULL_FACE))
905 Standard_Integer myReadBuffer; //!< current read buffer
906 OpenGl_DrawBuffers myDrawBuffers; //!< current draw buffers
907 unsigned int myDefaultVao; //!< default Vertex Array Object
908 Standard_Boolean myIsGlDebugCtx; //!< debug context initialization state
909 TCollection_AsciiString myVendor; //!< Graphics Driver's vendor
910 TColStd_PackedMapOfInteger myFilters[6]; //!< messages suppressing filter (for sources from GL_DEBUG_SOURCE_API_ARB to GL_DEBUG_SOURCE_OTHER_ARB)
911 unsigned int myResolution; //!< Pixels density (PPI), defines scaling factor for parameters like text size
912 Standard_ShortReal myResolutionRatio; //!< scaling factor for parameters like text size
913 //! to be properly displayed on device (screen / printer)
914 Standard_ShortReal myLineWidthScale; //!< scaling factor for line width
915 Standard_ShortReal myRenderScale; //!< scaling factor for rendering resolution
916 Standard_ShortReal myRenderScaleInv; //!< scaling factor for rendering resolution (inverted value)
917 OpenGl_Material myMatFront; //!< current front material state (cached to reduce GL context updates)
918 OpenGl_Material myMatBack; //!< current back material state
922 //! Copying allowed only within Handles
923 OpenGl_Context (const OpenGl_Context& );
924 OpenGl_Context& operator= (const OpenGl_Context& );
928 #endif // _OpenGl_Context_H__