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