9752680fa4c7c50a05a3db49be541a93903db79b
[occt.git] / src / OpenGl / OpenGl_Context.hxx
1 // Created on: 2012-01-26
2 // Created by: Kirill GAVRILOV
3 // Copyright (c) 2012-2012 OPEN CASCADE SAS
4 //
5 // The content of this file is subject to the Open CASCADE Technology Public
6 // License Version 6.5 (the "License"). You may not use the content of this file
7 // except in compliance with the License. Please obtain a copy of the License
8 // at http://www.opencascade.org and read it completely before using this file.
9 //
10 // The Initial Developer of the Original Code is Open CASCADE S.A.S., having its
11 // main offices at: 1, place des Freres Montgolfier, 78280 Guyancourt, France.
12 //
13 // The Original Code and all software distributed under the License is
14 // distributed on an "AS IS" basis, without warranty of any kind, and the
15 // Initial Developer hereby disclaims all such warranties, including without
16 // limitation, any warranties of merchantability, fitness for a particular
17 // purpose or non-infringement. Please see the License for the specific terms
18 // and conditions governing the rights and limitations under the License.
19
20 #ifndef _OpenGl_Context_H__
21 #define _OpenGl_Context_H__
22
23 #include <Aspect_Handle.hxx>
24 #include <Aspect_Drawable.hxx>
25 #include <Aspect_Display.hxx>
26 #include <Aspect_RenderingContext.hxx>
27 #include <Handle_OpenGl_Context.hxx>
28 #include <NCollection_DataMap.hxx>
29 #include <NCollection_Handle.hxx>
30 #include <NCollection_Queue.hxx>
31 #include <OpenGl_Resource.hxx>
32 #include <Standard_Transient.hxx>
33 #include <TCollection_AsciiString.hxx>
34 #include <Handle_OpenGl_Context.hxx>
35
36 //! Forward declarations
37 struct OpenGl_GlCore12;
38 struct OpenGl_GlCore13;
39 struct OpenGl_GlCore14;
40 struct OpenGl_GlCore15;
41 struct OpenGl_GlCore20;
42 struct OpenGl_ArbVBO;
43 struct OpenGl_ArbTBO;
44 struct OpenGl_ArbIns;
45 struct OpenGl_ExtFBO;
46 struct OpenGl_ExtGS;
47
48 //! This class generalize access to the GL context and available extensions.
49 //!
50 //! Functions are grouped into structures and accessed as fields.
51 //! You should check the group for NULL before usage (if group is not NULL
52 //! then all functions are available):
53 //! @code
54 //!   if (myContext->core20 != NULL)
55 //!   {
56 //!     myGlProgram = myContext->core20->glCreateProgram();
57 //!     .. do more stuff ..
58 //!   }
59 //!   else
60 //!   {
61 //!     .. compatibility with outdated configurations ..
62 //!   }
63 //! @endcode
64 //!
65 //! Current implementation provide access to OpenGL core functionality up to 2.0 version
66 //! (core12, core13, core14, core15, fields core20).
67 //! within several extensions (arbVBO, extFBO, etc.).
68 //!
69 //! Simplified extensions classification:
70 //!  - prefixed with NV, AMD, ATI are vendor-specific (however may be provided by other vendors in some cases);
71 //!  - prefixed with EXT are accepted by 2+ vendors;
72 //!  - prefixed with ARB are accepted by Architecture Review Board and are candidates
73 //!    for inclusion into GL core functionality.
74 //! Some functionality can be represented in several extensions simultaneously.
75 //! In this case developer should be careful because different specification may differ
76 //! in aspects (like enumeration values and error-handling).
77 //!
78 //! Notice that some systems provide mechanisms to simultaneously incorporate with GL contexts
79 //! with different capabilities. Thats why OpenGl_Context should be initialized and used
80 //! for each GL context individually.
81 class OpenGl_Context : public Standard_Transient
82 {
83 public:
84
85   //! Empty constructor. You should call Init() to perform initialization with bound GL context.
86   Standard_EXPORT OpenGl_Context();
87
88   //! Destructor.
89   Standard_EXPORT virtual ~OpenGl_Context();
90
91   //! Share GL context resources.
92   //! theShareCtx - handle to context to retrieve handles to shared resources.
93   Standard_EXPORT void Share (const Handle(OpenGl_Context)& theShareCtx);
94
95   //! Initialize available extensions.
96   //! GL context should be active!
97   Standard_EXPORT Standard_Boolean Init();
98
99 #if (defined(_WIN32) || defined(__WIN32__))
100   Standard_EXPORT Standard_Boolean Init (const Aspect_Handle           theWindow,
101                                          const Aspect_Handle           theWindowDC,
102                                          const Aspect_RenderingContext theGContext);
103 #else
104   Standard_EXPORT Standard_Boolean Init (const Aspect_Drawable         theWindow,
105                                          const Aspect_Display          theDisplay,
106                                          const Aspect_RenderingContext theGContext);
107 #endif
108
109   //! Check if theExtName extension is supported by active GL context.
110   Standard_EXPORT Standard_Boolean CheckExtension (const char* theExtName) const;
111
112   //! Auxiliary template to retrieve GL function pointer.
113   //! Pointer to function retrieved from library is statically casted
114   //! to requested type - there no way to check real signature of exported function.
115   //! The context should be bound before call.
116   template <typename FuncType_t>
117   Standard_Boolean FindProc (const char* theFuncName,
118                              FuncType_t& theFuncPtr)
119   {
120     theFuncPtr = (FuncType_t )findProc (theFuncName);
121     return (theFuncPtr != NULL);
122   }
123
124   //! @return true if detected GL version is greater or equal to requested one.
125   inline Standard_Boolean IsGlGreaterEqual (const Standard_Integer theVerMajor,
126                                             const Standard_Integer theVerMinor)
127   {
128     return (myGlVerMajor >  theVerMajor)
129         || (myGlVerMajor == theVerMajor && myGlVerMinor >= theVerMinor);
130   }
131
132   //! Clean up errors stack for this GL context (glGetError() in loop).
133   Standard_EXPORT void ResetErrors();
134
135   //! This method uses system-dependent API to retrieve information
136   //! about GL context bound to the current thread.
137   //! @return true if current thread is bound to this GL context
138   Standard_EXPORT Standard_Boolean IsCurrent() const;
139
140   //! Activates current context.
141   //! Class should be initialized with appropriate info.
142   Standard_EXPORT Standard_Boolean MakeCurrent();
143
144   //! Swap front/back buffers for this GL context (should be activated before!).
145   Standard_EXPORT void SwapBuffers();
146
147   //! Return true if active mode is GL_FEEDBACK (cached state)
148   Standard_EXPORT Standard_Boolean IsFeedback() const;
149
150   //! Setup feedback mode cached state
151   Standard_EXPORT void SetFeedback (const Standard_Boolean theFeedbackOn);
152
153   //! This function retrieves information from GL about free GPU memory that is:
154   //!  - OS-dependent. On some OS it is per-process and on others - for entire system.
155   //!  - Vendor-dependent. Currently available only on NVIDIA and AMD/ATi drivers only.
156   //!  - Numbers meaning may vary.
157   //! You should use this info only for diagnostics purposes.
158   //! @return free GPU dedicated memory in bytes.
159   Standard_EXPORT Standard_Size AvailableMemory() const;
160
161   //! This function retrieves information from GL about GPU memory
162   //! and contains more vendor-specific values than AvailableMemory().
163   Standard_EXPORT TCollection_AsciiString MemoryInfo() const;
164
165   //! Access shared resource by its name.
166   //! @param  theKey - unique identifier;
167   //! @return handle to shared resource or NULL.
168   Standard_EXPORT const Handle(OpenGl_Resource)& GetResource (const TCollection_AsciiString& theKey) const;
169
170   //! Access shared resource by its name.
171   //! @param  theKey   - unique identifier;
172   //! @param  theValue - handle to fill;
173   //! @return true if resource was shared.
174   template<typename TheHandleType>
175   Standard_Boolean GetResource (const TCollection_AsciiString& theKey,
176                                 TheHandleType&                 theValue) const
177   {
178     const Handle(OpenGl_Resource)& aResource = GetResource (theKey);
179     if (aResource.IsNull())
180     {
181       return Standard_False;
182     }
183
184     theValue = TheHandleType::DownCast (aResource);
185     return !theValue.IsNull();
186   }
187
188   //! Register shared resource.
189   //! Notice that after registration caller shouldn't release it by himself -
190   //! it will be automatically released on context destruction.
191   //! @param theKey      - unique identifier, shouldn't be empty;
192   //! @param theResource - new resource to register, shouldn't be NULL.
193   Standard_EXPORT Standard_Boolean ShareResource (const TCollection_AsciiString& theKey,
194                                                   const Handle(OpenGl_Resource)& theResource);
195
196   //! Release shared resource.
197   //! If there are more than one reference to this resource
198   //! (also used by some other existing object) then call will be ignored.
199   //! This means that current object itself should nullify handle before this call.
200   //! Notice that this is unrecommended operation at all and should be used
201   //! only in case of fat resources to release memory for other needs.
202   //! @param  theKey - unique identifier.
203   Standard_EXPORT void ReleaseResource (const TCollection_AsciiString& theKey);
204
205   //! Append resource to queue for delayed clean up.
206   //! Resources in this queue will be released at next redraw call.
207   Standard_EXPORT void DelayedRelease (Handle(OpenGl_Resource)& theResource);
208
209   //! Clean up the delayed release queue.
210   Standard_EXPORT void ReleaseDelayed();
211
212   //! @return maximum degree of anisotropy texture filter
213   Standard_EXPORT Standard_Integer MaxDegreeOfAnisotropy() const;
214
215   //! @return value for GL_MAX_TEXTURE_SIZE
216   Standard_EXPORT Standard_Integer MaxTextureSize() const;
217
218 private:
219
220   //! Wrapper to system function to retrieve GL function pointer by name.
221   Standard_EXPORT void* findProc (const char* theFuncName);
222
223   //! Read OpenGL version information from active context.
224   Standard_EXPORT void readGlVersion();
225
226   //! Private initialization function that should be called only once.
227   Standard_EXPORT void init();
228
229 public: // core profiles
230
231   OpenGl_GlCore12* core12;
232   OpenGl_GlCore13* core13;
233   OpenGl_GlCore14* core14;
234   OpenGl_GlCore15* core15;
235   OpenGl_GlCore20* core20;
236
237 public: // extensions
238
239   Standard_Boolean arbNPTW; //!< GL_ARB_texture_non_power_of_two
240   OpenGl_ArbVBO*   arbVBO;  //!< GL_ARB_vertex_buffer_object
241   OpenGl_ArbTBO*   arbTBO;  //!< GL_ARB_texture_buffer_object
242   OpenGl_ArbIns*   arbIns;  //!< GL_ARB_draw_instanced
243   OpenGl_ExtFBO*   extFBO;  //!< GL_EXT_framebuffer_object
244   OpenGl_ExtGS*    extGS;   //!< GL_EXT_geometry_shader4
245   Standard_Boolean extBgra; //!< GL_EXT_bgra
246   Standard_Boolean extAnis; //!< GL_EXT_texture_filter_anisotropic
247   Standard_Boolean atiMem;  //!< GL_ATI_meminfo
248   Standard_Boolean nvxMem;  //!< GL_NVX_gpu_memory_info
249
250 private: // system-dependent fields
251
252 #if (defined(_WIN32) || defined(__WIN32__))
253   Aspect_Handle           myWindow;   //!< window handle (owner of GL context) : HWND
254   Aspect_Handle           myWindowDC; //!< Device Descriptor handle : HDC
255   Aspect_RenderingContext myGContext; //!< Rendering Context handle : HGLRC
256 #else
257   Aspect_Drawable         myWindow;   //!< window handle (owner of GL context) : GLXDrawable
258   Aspect_Display          myDisplay;  //!< connection to the X-server : Display*
259   Aspect_RenderingContext myGContext; //!< X-GLX rendering context : GLXContext
260 #endif
261
262 private: // context info
263
264   typedef NCollection_DataMap<TCollection_AsciiString, Handle(OpenGl_Resource)> OpenGl_ResourcesMap;
265   typedef NCollection_Handle<OpenGl_ResourcesMap> Handle(OpenGl_ResourcesMap);
266   typedef NCollection_Queue<Handle(OpenGl_Resource)> OpenGl_ResourcesQueue;
267   typedef NCollection_Handle<OpenGl_ResourcesQueue> Handle(OpenGl_ResourcesQueue);
268
269   Handle(OpenGl_ResourcesMap)   mySharedResources; //!< shared resourced with unique identification key
270   Handle(OpenGl_ResourcesQueue) myReleaseQueue;    //!< queue of resources for delayed clean up
271
272   void*            myGlLibHandle;   //!< optional handle to GL library
273   OpenGl_GlCore20* myGlCore20;      //!< common structure for GL core functions upto 2.0
274   Standard_Integer myAnisoMax;      //!< maximum level of anisotropy texture filter
275   Standard_Integer myMaxTexDim;     //!< value for GL_MAX_TEXTURE_SIZE
276   Standard_Integer myGlVerMajor;    //!< cached GL version major number
277   Standard_Integer myGlVerMinor;    //!< cached GL version minor number
278   Standard_Boolean myIsFeedback;    //!< flag indicates GL_FEEDBACK mode
279   Standard_Boolean myIsInitialized; //!< flag indicates initialization state
280
281 private:
282
283   //! Copying allowed only within Handles
284   OpenGl_Context            (const OpenGl_Context& );
285   OpenGl_Context& operator= (const OpenGl_Context& );
286
287 public:
288
289   DEFINE_STANDARD_RTTI(OpenGl_Context) // Type definition
290
291   friend class OpenGl_Window;
292
293 };
294
295 #endif // _OpenGl_Context_H__