1694e17664dc12f055ddf62fe96ca5b26dbb1d82
[occt.git] / src / OpenGl / OpenGl_GraphicDriver.cxx
1 // Created on: 2011-10-20
2 // Created by: Sergey ZERCHANINOV
3 // Copyright (c) 2011-2013 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 #if defined(_WIN32)
17   #include <windows.h>
18 #endif
19
20 #include <OpenGl_GraphicDriver.hxx>
21 #include <OpenGl_Context.hxx>
22 #include <OpenGl_Flipper.hxx>
23 #include <OpenGl_GraduatedTrihedron.hxx>
24 #include <OpenGl_Group.hxx>
25 #include <OpenGl_View.hxx>
26 #include <OpenGl_StencilTest.hxx>
27 #include <OpenGl_Text.hxx>
28 #include <OpenGl_Workspace.hxx>
29
30 #include <Aspect_GraphicDeviceDefinitionError.hxx>
31 #include <Aspect_IdentDefinitionError.hxx>
32 #include <Graphic3d_StructureManager.hxx>
33 #include <Message_Messenger.hxx>
34 #include <OSD_Environment.hxx>
35 #include <Standard_NotImplemented.hxx>
36
37 IMPLEMENT_STANDARD_RTTIEXT(OpenGl_GraphicDriver,Graphic3d_GraphicDriver)
38
39 #if defined(_WIN32)
40   #include <WNT_Window.hxx>
41 #elif defined(__APPLE__) && !defined(MACOSX_USE_GLX)
42   #include <Cocoa_Window.hxx>
43 #else
44   #include <Xw_Window.hxx>
45 #endif
46
47 #if !defined(_WIN32) && !defined(__ANDROID__) && !defined(__QNX__) && !defined(__EMSCRIPTEN__) && (!defined(__APPLE__) || defined(MACOSX_USE_GLX))
48   #include <X11/Xlib.h> // XOpenDisplay()
49 #endif
50
51 #if defined(HAVE_EGL) || defined(HAVE_GLES2) || defined(OCCT_UWP) || defined(__ANDROID__) || defined(__QNX__) || defined(__EMSCRIPTEN__)
52   #include <EGL/egl.h>
53   #ifndef EGL_OPENGL_ES3_BIT
54     #define EGL_OPENGL_ES3_BIT 0x00000040
55   #endif
56 #endif
57
58 namespace
59 {
60   static const Handle(OpenGl_Context) TheNullGlCtx;
61
62 #if defined(HAVE_EGL) || defined(HAVE_GLES2) || defined(OCCT_UWP) || defined(__ANDROID__) || defined(__QNX__) || defined(__EMSCRIPTEN__)
63   //! Wrapper over eglChooseConfig() called with preferred defaults.
64   static EGLConfig chooseEglSurfConfig (EGLDisplay theDisplay)
65   {
66     EGLint aConfigAttribs[] =
67     {
68       EGL_RED_SIZE,     8,
69       EGL_GREEN_SIZE,   8,
70       EGL_BLUE_SIZE,    8,
71       EGL_ALPHA_SIZE,   0,
72       EGL_DEPTH_SIZE,   24,
73       EGL_STENCIL_SIZE, 8,
74     #if defined(GL_ES_VERSION_2_0)
75       EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
76     #else
77       EGL_RENDERABLE_TYPE, EGL_OPENGL_BIT,
78     #endif
79       EGL_NONE
80     };
81
82     EGLConfig aCfg = NULL;
83     EGLint aNbConfigs = 0;
84     for (Standard_Integer aGlesVer = 3; aGlesVer >= 2; --aGlesVer)
85     {
86     #if defined(GL_ES_VERSION_2_0)
87       aConfigAttribs[6 * 2 + 1] = aGlesVer == 3 ? EGL_OPENGL_ES3_BIT : EGL_OPENGL_ES2_BIT;
88     #else
89       if (aGlesVer == 2)
90       {
91         break;
92       }
93     #endif
94
95       if (eglChooseConfig (theDisplay, aConfigAttribs, &aCfg, 1, &aNbConfigs) == EGL_TRUE
96        && aCfg != NULL)
97       {
98         return aCfg;
99       }
100       eglGetError();
101
102       aConfigAttribs[4 * 2 + 1] = 16; // try config with smaller depth buffer
103       if (eglChooseConfig (theDisplay, aConfigAttribs, &aCfg, 1, &aNbConfigs) == EGL_TRUE
104        && aCfg != NULL)
105       {
106         return aCfg;
107       }
108       eglGetError();
109     }
110     return aCfg;
111   }
112 #endif
113 }
114
115 // =======================================================================
116 // function : OpenGl_GraphicDriver
117 // purpose  :
118 // =======================================================================
119 OpenGl_GraphicDriver::OpenGl_GraphicDriver (const Handle(Aspect_DisplayConnection)& theDisp,
120                                             const Standard_Boolean                  theToInitialize)
121 : Graphic3d_GraphicDriver (theDisp),
122   myIsOwnContext (Standard_False),
123 #if defined(HAVE_EGL) || defined(HAVE_GLES2) || defined(OCCT_UWP) || defined(__ANDROID__) || defined(__QNX__) || defined(__EMSCRIPTEN__)
124   myEglDisplay ((Aspect_Display )EGL_NO_DISPLAY),
125   myEglContext ((Aspect_RenderingContext )EGL_NO_CONTEXT),
126   myEglConfig  (NULL),
127 #endif
128   myCaps           (new OpenGl_Caps()),
129   myMapOfView      (1, NCollection_BaseAllocator::CommonBaseAllocator()),
130   myMapOfStructure (1, NCollection_BaseAllocator::CommonBaseAllocator())
131 {
132 #if !defined(_WIN32) && !defined(__ANDROID__) && !defined(__QNX__) && !defined(__EMSCRIPTEN__) && (!defined(__APPLE__) || defined(MACOSX_USE_GLX))
133   if (myDisplayConnection.IsNull())
134   {
135     //throw Aspect_GraphicDeviceDefinitionError("OpenGl_GraphicDriver: cannot connect to X server!");
136     return;
137   }
138
139   Display* aDisplay = myDisplayConnection->GetDisplay();
140   Bool toSync = ::getenv ("CSF_GraphicSync") != NULL
141              || ::getenv ("CALL_SYNCHRO_X")  != NULL;
142   XSynchronize (aDisplay, toSync);
143
144 #if !defined(HAVE_EGL) && !defined(HAVE_GLES2)
145   // does the server know about OpenGL & GLX?
146   int aDummy;
147   if (!XQueryExtension (aDisplay, "GLX", &aDummy, &aDummy, &aDummy))
148   {
149     ::Message::DefaultMessenger()->Send ("OpenGl_GraphicDriver, this system doesn't appear to support OpenGL!", Message_Warning);
150   }
151 #endif
152 #endif
153   if (theToInitialize
154   && !InitContext())
155   {
156     throw Aspect_GraphicDeviceDefinitionError("OpenGl_GraphicDriver: default context can not be initialized!");
157   }
158 }
159
160 // =======================================================================
161 // function : ~OpenGl_GraphicDriver
162 // purpose  :
163 // =======================================================================
164 OpenGl_GraphicDriver::~OpenGl_GraphicDriver()
165 {
166   ReleaseContext();
167 }
168
169 // =======================================================================
170 // function : ReleaseContext
171 // purpose  :
172 // =======================================================================
173 void OpenGl_GraphicDriver::ReleaseContext()
174 {
175   Handle(OpenGl_Context) aCtxShared;
176   for (NCollection_Map<Handle(OpenGl_View)>::Iterator aViewIter (myMapOfView);
177        aViewIter.More(); aViewIter.Next())
178   {
179     const Handle(OpenGl_View)& aView = aViewIter.Value();
180     const Handle(OpenGl_Window)& aWindow = aView->GlWindow();
181     if (aWindow.IsNull())
182     {
183       continue;
184     }
185
186     const Handle(OpenGl_Context)& aCtx = aWindow->GetGlContext();
187     if (aCtx->MakeCurrent()
188      && aCtxShared.IsNull())
189     {
190       aCtxShared = aCtx;
191     }
192   }
193
194   if (!aCtxShared.IsNull())
195   {
196     aCtxShared->MakeCurrent();
197   }
198   for (NCollection_Map<Handle(OpenGl_View)>::Iterator aViewIter (myMapOfView);
199        aViewIter.More(); aViewIter.Next())
200   {
201     const Handle(OpenGl_View)& aView = aViewIter.Value();
202     aView->ReleaseGlResources (aCtxShared);
203   }
204
205   for (NCollection_DataMap<Standard_Integer, OpenGl_Structure*>::Iterator aStructIt (myMapOfStructure);
206        aStructIt.More (); aStructIt.Next())
207   {
208     OpenGl_Structure* aStruct = aStructIt.ChangeValue();
209     aStruct->ReleaseGlResources (aCtxShared);
210   }
211
212   const bool isDeviceLost = !myMapOfStructure.IsEmpty();
213   for (NCollection_Map<Handle(OpenGl_View)>::Iterator aViewIter (myMapOfView);
214        aViewIter.More(); aViewIter.Next())
215   {
216     const Handle(OpenGl_View)& aView = aViewIter.Value();
217     if (isDeviceLost)
218     {
219       aView->StructureManager()->SetDeviceLost();
220     }
221
222     const Handle(OpenGl_Window)& aWindow = aView->GlWindow();
223     if (aWindow.IsNull())
224     {
225       continue;
226     }
227
228     aWindow->GetGlContext()->forcedRelease();
229   }
230
231 #if defined(HAVE_EGL) || defined(HAVE_GLES2) || defined(OCCT_UWP) || defined(__ANDROID__) || defined(__QNX__) || defined(__EMSCRIPTEN__)
232   if (myIsOwnContext)
233   {
234     if (myEglContext != (Aspect_RenderingContext )EGL_NO_CONTEXT)
235     {
236       if (eglMakeCurrent ((EGLDisplay )myEglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT) != EGL_TRUE)
237       {
238         ::Message::DefaultMessenger()->Send ("OpenGl_GraphicDriver, FAILED to release OpenGL context!", Message_Warning);
239       }
240       eglDestroyContext ((EGLDisplay )myEglDisplay, (EGLContext )myEglContext);
241     }
242
243     if (myEglDisplay != (Aspect_Display )EGL_NO_DISPLAY)
244     {
245       if (eglTerminate ((EGLDisplay )myEglDisplay) != EGL_TRUE)
246       {
247         ::Message::DefaultMessenger()->Send ("OpenGl_GraphicDriver, EGL, eglTerminate FAILED!", Message_Warning);
248       }
249     }
250   }
251
252   myEglDisplay = (Aspect_Display )EGL_NO_DISPLAY;
253   myEglContext = (Aspect_RenderingContext )EGL_NO_CONTEXT;
254   myEglConfig  = NULL;
255 #endif
256   myIsOwnContext = Standard_False;
257 }
258
259 // =======================================================================
260 // function : InitContext
261 // purpose  :
262 // =======================================================================
263 Standard_Boolean OpenGl_GraphicDriver::InitContext()
264 {
265   ReleaseContext();
266 #if defined(HAVE_EGL) || defined(HAVE_GLES2) || defined(OCCT_UWP) || defined(__ANDROID__) || defined(__QNX__) || defined(__EMSCRIPTEN__)
267
268 #if !defined(_WIN32) && !defined(__ANDROID__) && !defined(__QNX__) && !defined(__EMSCRIPTEN__) && (!defined(__APPLE__) || defined(MACOSX_USE_GLX))
269   if (myDisplayConnection.IsNull())
270   {
271     return Standard_False;
272   }
273   Display* aDisplay = myDisplayConnection->GetDisplay();
274   myEglDisplay = (Aspect_Display )eglGetDisplay (aDisplay);
275 #else
276   myEglDisplay = (Aspect_Display )eglGetDisplay (EGL_DEFAULT_DISPLAY);
277 #endif
278   if ((EGLDisplay )myEglDisplay == EGL_NO_DISPLAY)
279   {
280     ::Message::DefaultMessenger()->Send ("Error: no EGL display!", Message_Fail);
281     return Standard_False;
282   }
283
284   EGLint aVerMajor = 0; EGLint aVerMinor = 0;
285   if (eglInitialize ((EGLDisplay )myEglDisplay, &aVerMajor, &aVerMinor) != EGL_TRUE)
286   {
287     ::Message::DefaultMessenger()->Send ("Error: EGL display is unavailable!", Message_Fail);
288     return Standard_False;
289   }
290
291   myEglConfig = chooseEglSurfConfig ((EGLDisplay )myEglDisplay);
292   if (myEglConfig == NULL)
293   {
294     ::Message::DefaultMessenger()->Send ("Error: EGL does not provide compatible configurations!", Message_Fail);
295     return Standard_False;
296   }
297
298 #if defined(GL_ES_VERSION_2_0)
299   EGLint anEglCtxAttribs3[] = { EGL_CONTEXT_CLIENT_VERSION, 3, EGL_NONE, EGL_NONE };
300   EGLint anEglCtxAttribs2[] = { EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE, EGL_NONE };
301   if (eglBindAPI (EGL_OPENGL_ES_API) != EGL_TRUE)
302   {
303     ::Message::DefaultMessenger()->Send ("Error: EGL does not provide OpenGL ES client!", Message_Fail);
304     return Standard_False;
305   }
306   if (myCaps->contextMajorVersionUpper != 2)
307   {
308     myEglContext = (Aspect_RenderingContext )eglCreateContext ((EGLDisplay )myEglDisplay, myEglConfig, EGL_NO_CONTEXT, anEglCtxAttribs3);
309   }
310   if ((EGLContext )myEglContext == EGL_NO_CONTEXT)
311   {
312     myEglContext = (Aspect_RenderingContext )eglCreateContext ((EGLDisplay )myEglDisplay, myEglConfig, EGL_NO_CONTEXT, anEglCtxAttribs2);
313   }
314 #else
315   EGLint* anEglCtxAttribs = NULL;
316   if (eglBindAPI (EGL_OPENGL_API) != EGL_TRUE)
317   {
318     ::Message::DefaultMessenger()->Send ("Error: EGL does not provide OpenGL client!", Message_Fail);
319     return Standard_False;
320   }
321   myEglContext = (Aspect_RenderingContext )eglCreateContext ((EGLDisplay )myEglDisplay, myEglConfig, EGL_NO_CONTEXT, anEglCtxAttribs);
322 #endif
323
324   if ((EGLContext )myEglContext == EGL_NO_CONTEXT)
325   {
326     ::Message::DefaultMessenger()->Send ("Error: EGL is unable to create OpenGL context!", Message_Fail);
327     return Standard_False;
328   }
329   // eglMakeCurrent() fails or even crash with EGL_NO_SURFACE on some implementations
330   //if (eglMakeCurrent ((EGLDisplay )myEglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, (EGLContext )myEglContext) != EGL_TRUE)
331   //{
332   //  ::Message::DefaultMessenger()->Send ("Error: EGL is unable bind OpenGL context!", Message_Fail);
333   //  return Standard_False;
334   //}
335 #endif
336   myIsOwnContext = Standard_True;
337   return Standard_True;
338 }
339
340 #if defined(HAVE_EGL) || defined(HAVE_GLES2) || defined(OCCT_UWP) || defined(__ANDROID__) || defined(__QNX__) || defined(__EMSCRIPTEN__)
341 // =======================================================================
342 // function : InitEglContext
343 // purpose  :
344 // =======================================================================
345 Standard_Boolean OpenGl_GraphicDriver::InitEglContext (Aspect_Display          theEglDisplay,
346                                                        Aspect_RenderingContext theEglContext,
347                                                        void*                   theEglConfig)
348 {
349   ReleaseContext();
350 #if !defined(_WIN32) && !defined(__ANDROID__) && !defined(__QNX__) && !defined(__EMSCRIPTEN__) && (!defined(__APPLE__) || defined(MACOSX_USE_GLX))
351   if (myDisplayConnection.IsNull())
352   {
353     return Standard_False;
354   }
355 #endif
356
357   if ((EGLDisplay )theEglDisplay == EGL_NO_DISPLAY
358    || (EGLContext )theEglContext == EGL_NO_CONTEXT)
359   {
360     return Standard_False;
361   }
362   myEglDisplay = theEglDisplay;
363   myEglContext = theEglContext;
364   myEglConfig  = theEglConfig;
365   if (theEglConfig == NULL)
366   {
367     myEglConfig = chooseEglSurfConfig ((EGLDisplay )myEglDisplay);
368     if (myEglConfig == NULL)
369     {
370       ::Message::DefaultMessenger()->Send ("Error: EGL does not provide compatible configurations!", Message_Fail);
371       return Standard_False;
372     }
373   }
374   return Standard_True;
375 }
376 #endif
377
378 // =======================================================================
379 // function : InquireLimit
380 // purpose  :
381 // =======================================================================
382 Standard_Integer OpenGl_GraphicDriver::InquireLimit (const Graphic3d_TypeOfLimit theType) const
383 {
384   const Handle(OpenGl_Context)& aCtx = GetSharedContext();
385   switch (theType)
386   {
387     case Graphic3d_TypeOfLimit_MaxNbLights:
388       return Graphic3d_ShaderProgram::THE_MAX_LIGHTS_DEFAULT;
389     case Graphic3d_TypeOfLimit_MaxNbClipPlanes:
390       return !aCtx.IsNull() ? aCtx->MaxClipPlanes() : 0;
391     case Graphic3d_TypeOfLimit_MaxNbViews:
392       return 10000;
393     case Graphic3d_TypeOfLimit_MaxTextureSize:
394       return !aCtx.IsNull() ? aCtx->MaxTextureSize() : 1024;
395     case Graphic3d_TypeOfLimit_MaxCombinedTextureUnits:
396       return !aCtx.IsNull() ? aCtx->MaxCombinedTextureUnits() : 1;
397     case Graphic3d_TypeOfLimit_MaxMsaa:
398       return !aCtx.IsNull() ? aCtx->MaxMsaaSamples() : 0;
399     case Graphic3d_TypeOfLimit_MaxViewDumpSizeX:
400       return !aCtx.IsNull() ? aCtx->MaxDumpSizeX() : 1024;
401     case Graphic3d_TypeOfLimit_MaxViewDumpSizeY:
402       return !aCtx.IsNull() ? aCtx->MaxDumpSizeY() : 1024;
403     case Graphic3d_TypeOfLimit_HasRayTracing:
404       return (!aCtx.IsNull() && aCtx->HasRayTracing()) ? 1 : 0;
405     case Graphic3d_TypeOfLimit_HasRayTracingTextures:
406       return (!aCtx.IsNull() && aCtx->HasRayTracingTextures()) ? 1 : 0;
407     case Graphic3d_TypeOfLimit_HasRayTracingAdaptiveSampling:
408       return (!aCtx.IsNull() && aCtx->HasRayTracingAdaptiveSampling()) ? 1 : 0;
409     case Graphic3d_TypeOfLimit_HasRayTracingAdaptiveSamplingAtomic:
410       return (!aCtx.IsNull() && aCtx->HasRayTracingAdaptiveSamplingAtomic()) ? 1 : 0;
411     case Graphic3d_TypeOfLimit_HasSRGB:
412       return (!aCtx.IsNull() && aCtx->HasSRGB()) ? 1 : 0;
413     case Graphic3d_TypeOfLimit_HasBlendedOit:
414       return (!aCtx.IsNull()
415             && aCtx->hasDrawBuffers != OpenGl_FeatureNotAvailable
416             && (aCtx->hasFloatBuffer != OpenGl_FeatureNotAvailable || aCtx->hasHalfFloatBuffer != OpenGl_FeatureNotAvailable)) ? 1 : 0;
417     case Graphic3d_TypeOfLimit_HasBlendedOitMsaa:
418       return (!aCtx.IsNull()
419             && aCtx->hasSampleVariables != OpenGl_FeatureNotAvailable
420             && (InquireLimit (Graphic3d_TypeOfLimit_HasBlendedOit) == 1)) ? 1 : 0;
421     case Graphic3d_TypeOfLimit_HasFlatShading:
422       return !aCtx.IsNull() && aCtx->hasFlatShading != OpenGl_FeatureNotAvailable ? 1 : 0;
423     case Graphic3d_TypeOfLimit_IsWorkaroundFBO:
424       return !aCtx.IsNull() && aCtx->MaxTextureSize() != aCtx->MaxDumpSizeX() ? 1 : 0;
425     case Graphic3d_TypeOfLimit_HasMeshEdges:
426       return !aCtx.IsNull() && aCtx->hasGeometryStage != OpenGl_FeatureNotAvailable ? 1 : 0;
427     case Graphic3d_TypeOfLimit_NB:
428       return 0;
429   }
430   return 0;
431 }
432
433 // =======================================================================
434 // function : DefaultTextHeight
435 // purpose  :
436 // =======================================================================
437 Standard_ShortReal OpenGl_GraphicDriver::DefaultTextHeight() const
438 {
439   return 16.;
440 }
441
442 // =======================================================================
443 // function : EnableVBO
444 // purpose  :
445 // =======================================================================
446 void OpenGl_GraphicDriver::EnableVBO (const Standard_Boolean theToTurnOn)
447 {
448   myCaps->vboDisable = !theToTurnOn;
449 }
450
451 // =======================================================================
452 // function : GetSharedContext
453 // purpose  :
454 // =======================================================================
455 const Handle(OpenGl_Context)& OpenGl_GraphicDriver::GetSharedContext (bool theBound) const
456 {
457   if (myMapOfView.IsEmpty())
458   {
459     return TheNullGlCtx;
460   }
461
462   for (NCollection_Map<Handle(OpenGl_View)>::Iterator aViewIter (myMapOfView); aViewIter.More(); aViewIter.Next())
463   {
464     if (const Handle(OpenGl_Window)& aWindow = aViewIter.Value()->GlWindow())
465     {
466       if (!theBound)
467       {
468         return aWindow->GetGlContext();
469       }
470       else if (aWindow->GetGlContext()->IsCurrent())
471       {
472         return aWindow->GetGlContext();
473       }
474     }
475   }
476
477   return TheNullGlCtx;
478 }
479
480 // =======================================================================
481 // function : MemoryInfo
482 // purpose  :
483 // =======================================================================
484 Standard_Boolean OpenGl_GraphicDriver::MemoryInfo (Standard_Size&           theFreeBytes,
485                                                    TCollection_AsciiString& theInfo) const
486 {
487   // this is extra work (for OpenGl_Context initialization)...
488   OpenGl_Context aGlCtx;
489   if (!aGlCtx.Init())
490   {
491     return Standard_False;
492   }
493   theFreeBytes = aGlCtx.AvailableMemory();
494   theInfo      = aGlCtx.MemoryInfo();
495   return !theInfo.IsEmpty();
496 }
497
498 // =======================================================================
499 // function : SetBuffersNoSwap
500 // purpose  :
501 // =======================================================================
502 void OpenGl_GraphicDriver::SetBuffersNoSwap (const Standard_Boolean theIsNoSwap)
503 {
504   myCaps->buffersNoSwap = theIsNoSwap;
505 }
506
507 // =======================================================================
508 // function : TextSize
509 // purpose  :
510 // =======================================================================
511 void OpenGl_GraphicDriver::TextSize (const Handle(Graphic3d_CView)& theView,
512                                      const Standard_CString         theText,
513                                      const Standard_ShortReal       theHeight,
514                                      Standard_ShortReal&            theWidth,
515                                      Standard_ShortReal&            theAscent,
516                                      Standard_ShortReal&            theDescent) const
517 {
518   const Handle(OpenGl_Context)& aCtx = GetSharedContext();
519   if (aCtx.IsNull())
520   {
521     return;
522   }
523
524   const Standard_ShortReal aHeight = (theHeight < 2.0f) ? DefaultTextHeight() : theHeight;
525   OpenGl_Aspects aTextAspect;
526   TCollection_ExtendedString anExtText = theText;
527   NCollection_String aText (anExtText.ToExtString());
528   OpenGl_Text::StringSize(aCtx, aText, aTextAspect, aHeight, theView->RenderingParams().Resolution, theWidth, theAscent, theDescent);
529 }
530
531 //=======================================================================
532 //function : InsertLayerBefore
533 //purpose  :
534 //=======================================================================
535 void OpenGl_GraphicDriver::InsertLayerBefore (const Graphic3d_ZLayerId theLayerId,
536                                               const Graphic3d_ZLayerSettings& theSettings,
537                                               const Graphic3d_ZLayerId theLayerAfter)
538 {
539   base_type::InsertLayerBefore (theLayerId, theSettings, theLayerAfter);
540
541   // Add layer to all views
542   for (NCollection_Map<Handle(OpenGl_View)>::Iterator aViewIt (myMapOfView); aViewIt.More(); aViewIt.Next())
543   {
544     aViewIt.Value()->InsertLayerBefore (theLayerId, theSettings, theLayerAfter);
545   }
546 }
547
548 //=======================================================================
549 //function : InsertLayerAfter
550 //purpose  :
551 //=======================================================================
552 void OpenGl_GraphicDriver::InsertLayerAfter (const Graphic3d_ZLayerId theNewLayerId,
553                                              const Graphic3d_ZLayerSettings& theSettings,
554                                              const Graphic3d_ZLayerId theLayerBefore)
555 {
556   base_type::InsertLayerAfter (theNewLayerId, theSettings, theLayerBefore);
557
558   // Add layer to all views
559   for (NCollection_Map<Handle(OpenGl_View)>::Iterator aViewIt (myMapOfView); aViewIt.More(); aViewIt.Next())
560   {
561     aViewIt.Value()->InsertLayerAfter (theNewLayerId, theSettings, theLayerBefore);
562   }
563 }
564
565 //=======================================================================
566 //function : RemoveZLayer
567 //purpose  :
568 //=======================================================================
569 void OpenGl_GraphicDriver::RemoveZLayer (const Graphic3d_ZLayerId theLayerId)
570 {
571   base_type::RemoveZLayer (theLayerId);
572
573   // Remove layer from all of the views
574   for (NCollection_Map<Handle(OpenGl_View)>::Iterator aViewIt (myMapOfView); aViewIt.More(); aViewIt.Next())
575   {
576     aViewIt.Value()->RemoveZLayer (theLayerId);
577   }
578
579   // Unset Z layer for all of the structures.
580   for (NCollection_DataMap<Standard_Integer, OpenGl_Structure*>::Iterator aStructIt (myMapOfStructure); aStructIt.More(); aStructIt.Next())
581   {
582     OpenGl_Structure* aStruct = aStructIt.ChangeValue ();
583     if (aStruct->ZLayer() == theLayerId)
584       aStruct->SetZLayer (Graphic3d_ZLayerId_Default);
585   }
586 }
587
588 //=======================================================================
589 //function : SetZLayerSettings
590 //purpose  :
591 //=======================================================================
592 void OpenGl_GraphicDriver::SetZLayerSettings (const Graphic3d_ZLayerId theLayerId,
593                                               const Graphic3d_ZLayerSettings& theSettings)
594 {
595   base_type::SetZLayerSettings (theLayerId, theSettings);
596
597   // Change Z layer settings in all managed views
598   for (NCollection_Map<Handle(OpenGl_View)>::Iterator aViewIt (myMapOfView); aViewIt.More(); aViewIt.Next())
599   {
600     aViewIt.Value()->SetZLayerSettings (theLayerId, theSettings);
601   }
602 }
603
604 // =======================================================================
605 // function : Structure
606 // purpose  :
607 // =======================================================================
608 Handle(Graphic3d_CStructure) OpenGl_GraphicDriver::CreateStructure (const Handle(Graphic3d_StructureManager)& theManager)
609 {
610   Handle(OpenGl_Structure) aStructure = new OpenGl_Structure (theManager);
611   myMapOfStructure.Bind (aStructure->Id, aStructure.operator->());
612   return aStructure;
613 }
614
615 // =======================================================================
616 // function : Structure
617 // purpose  :
618 // =======================================================================
619 void OpenGl_GraphicDriver::RemoveStructure (Handle(Graphic3d_CStructure)& theCStructure)
620 {
621   OpenGl_Structure* aStructure = NULL;
622   if (!myMapOfStructure.Find (theCStructure->Id, aStructure))
623   {
624     return;
625   }
626
627   myMapOfStructure.UnBind (theCStructure->Id);
628   aStructure->Release (GetSharedContext());
629   theCStructure.Nullify();
630 }
631
632 // =======================================================================
633 // function : CreateView
634 // purpose  :
635 // =======================================================================
636 Handle(Graphic3d_CView) OpenGl_GraphicDriver::CreateView (const Handle(Graphic3d_StructureManager)& theMgr)
637 {
638   Handle(OpenGl_View) aView = new OpenGl_View (theMgr, this, myCaps, &myStateCounter);
639   myMapOfView.Add (aView);
640   for (NCollection_List<Handle(Graphic3d_Layer)>::Iterator aLayerIter (myLayers); aLayerIter.More(); aLayerIter.Next())
641   {
642     const Handle(Graphic3d_Layer)& aLayer = aLayerIter.Value();
643     aView->InsertLayerAfter (aLayer->LayerId(), aLayer->LayerSettings(), Graphic3d_ZLayerId_UNKNOWN);
644   }
645   return aView;
646 }
647
648 // =======================================================================
649 // function : RemoveView
650 // purpose  :
651 // =======================================================================
652 void OpenGl_GraphicDriver::RemoveView (const Handle(Graphic3d_CView)& theView)
653 {
654   Handle(OpenGl_Context) aCtx = GetSharedContext();
655   Handle(OpenGl_View) aView   = Handle(OpenGl_View)::DownCast (theView);
656   if (aView.IsNull())
657   {
658     return;
659   }
660
661   if (!myMapOfView.Remove (aView))
662   {
663     return;
664   }
665
666   Handle(OpenGl_Window) aWindow = aView->GlWindow();
667   if (!aWindow.IsNull()
668     && aWindow->GetGlContext()->MakeCurrent())
669   {
670     aCtx = aWindow->GetGlContext();
671   }
672   else
673   {
674     // try to hijack another context if any
675     const Handle(OpenGl_Context)& anOtherCtx = GetSharedContext();
676     if (!anOtherCtx.IsNull()
677       && anOtherCtx != aWindow->GetGlContext())
678     {
679       aCtx = anOtherCtx;
680       aCtx->MakeCurrent();
681     }
682   }
683
684   aView->ReleaseGlResources (aCtx);
685   if (myMapOfView.IsEmpty())
686   {
687     // The last view removed but some objects still present.
688     // Release GL resources now without object destruction.
689     for (NCollection_DataMap<Standard_Integer, OpenGl_Structure*>::Iterator aStructIt (myMapOfStructure);
690          aStructIt.More (); aStructIt.Next())
691     {
692       OpenGl_Structure* aStruct = aStructIt.ChangeValue();
693       aStruct->ReleaseGlResources (aCtx);
694     }
695
696     if (!myMapOfStructure.IsEmpty())
697     {
698       aView->StructureManager()->SetDeviceLost();
699     }
700   }
701 }
702
703 // =======================================================================
704 // function : Window
705 // purpose  :
706 // =======================================================================
707 Handle(OpenGl_Window) OpenGl_GraphicDriver::CreateRenderWindow (const Handle(Aspect_Window)&  theWindow,
708                                                                 const Aspect_RenderingContext theContext)
709 {
710   Handle(OpenGl_Context) aShareCtx = GetSharedContext();
711   Handle(OpenGl_Window) aWindow = new OpenGl_Window (this, theWindow, theContext, myCaps, aShareCtx);
712   return aWindow;
713 }
714
715 //=======================================================================
716 //function : ViewExists
717 //purpose  :
718 //=======================================================================
719 Standard_Boolean OpenGl_GraphicDriver::ViewExists (const Handle(Aspect_Window)& AWindow, Handle(Graphic3d_CView)& theView)
720 {
721   Standard_Boolean isExist = Standard_False;
722
723   // Parse the list of views to find
724   // a view with the specified window
725
726 #if defined(_WIN32) && !defined(OCCT_UWP)
727   const Handle(WNT_Window) THEWindow = Handle(WNT_Window)::DownCast (AWindow);
728   Aspect_Handle TheSpecifiedWindowId = THEWindow->HWindow ();
729 #elif defined(__APPLE__) && !defined(MACOSX_USE_GLX)
730   const Handle(Cocoa_Window) THEWindow = Handle(Cocoa_Window)::DownCast (AWindow);
731   #if defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE
732     UIView* TheSpecifiedWindowId = THEWindow->HView();
733   #else
734     NSView* TheSpecifiedWindowId = THEWindow->HView();
735   #endif
736 #elif defined(__ANDROID__) || defined(__QNX__) || defined(__EMSCRIPTEN__) || defined(OCCT_UWP)
737   (void )AWindow;
738   int TheSpecifiedWindowId = -1;
739 #else
740   const Handle(Xw_Window) THEWindow = Handle(Xw_Window)::DownCast (AWindow);
741   int TheSpecifiedWindowId = int (THEWindow->XWindow ());
742 #endif
743
744   NCollection_Map<Handle(OpenGl_View)>::Iterator aViewIt (myMapOfView);
745   for(; aViewIt.More(); aViewIt.Next())
746   {
747     const Handle(OpenGl_View)& aView = aViewIt.Value();
748     if (aView->IsDefined() && aView->IsActive())
749     {
750       const Handle(Aspect_Window) AspectWindow = aView->Window();
751
752 #if defined(_WIN32) && !defined(OCCT_UWP)
753       const Handle(WNT_Window) theWindow = Handle(WNT_Window)::DownCast (AspectWindow);
754       Aspect_Handle TheWindowIdOfView = theWindow->HWindow ();
755 #elif defined(__APPLE__) && !defined(MACOSX_USE_GLX)
756       const Handle(Cocoa_Window) theWindow = Handle(Cocoa_Window)::DownCast (AspectWindow);
757       #if defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE
758         UIView* TheWindowIdOfView = theWindow->HView();
759       #else
760         NSView* TheWindowIdOfView = theWindow->HView();
761       #endif
762 #elif defined(__ANDROID__) || defined(__QNX__) || defined(__EMSCRIPTEN__) || defined(OCCT_UWP)
763       int TheWindowIdOfView = 0;
764 #else
765       const Handle(Xw_Window) theWindow = Handle(Xw_Window)::DownCast (AspectWindow);
766       int TheWindowIdOfView = int (theWindow->XWindow ());
767 #endif  // WNT
768       // Comparaison on window IDs
769       if (TheWindowIdOfView == TheSpecifiedWindowId)
770       {
771         isExist = Standard_True;
772         theView = aView;
773       }
774     }
775   }
776
777   return isExist;
778 }
779
780 //=======================================================================
781 //function : setDeviceLost
782 //purpose  :
783 //=======================================================================
784 void OpenGl_GraphicDriver::setDeviceLost()
785 {
786   if (myMapOfStructure.IsEmpty())
787   {
788     return;
789   }
790
791   for (NCollection_Map<Handle(OpenGl_View)>::Iterator aViewIter (myMapOfView); aViewIter.More(); aViewIter.Next())
792   {
793     const Handle(OpenGl_View)& aView = aViewIter.Value();
794     if (aView->myWasRedrawnGL)
795     {
796       aView->StructureManager()->SetDeviceLost();
797     }
798   }
799 }