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