1 // Created on: 2011-09-20
2 // Created by: Sergey ZERCHANINOV
3 // Copyright (c) 2011-2012 OPEN CASCADE SAS
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.
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.
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.
21 #include <InterfaceGraphic.hxx>
23 #include <OpenGl_Window.hxx>
25 #include <OpenGl_Context.hxx>
26 #include <OpenGl_Display.hxx>
27 #include <OpenGl_ResourceCleaner.hxx>
28 #include <OpenGl_ResourceTexture.hxx>
30 #include <Aspect_GraphicDeviceDefinitionError.hxx>
31 #include <TCollection_AsciiString.hxx>
33 #include <GL/glu.h> // gluOrtho2D()
35 IMPLEMENT_STANDARD_HANDLE(OpenGl_Window,MMgt_TShared)
36 IMPLEMENT_STANDARD_RTTIEXT(OpenGl_Window,MMgt_TShared)
40 static const TEL_COLOUR THE_DEFAULT_BG_COLOR = { { 0.F, 0.F, 0.F, 1.F } };
42 static GLCONTEXT ThePreviousCtx = 0; // to share GL resources
43 #if (!defined(_WIN32) && !defined(__WIN32__))
44 static GLXContext TheDeadGlxCtx; // Context to be destroyed
45 static Display* TheDeadGlxDpy; // Display associated with TheDeadGlxCtx
48 #if (defined(_WIN32) || defined(__WIN32__))
49 static int find_pixel_format (HDC hDC, PIXELFORMATDESCRIPTOR* pfd, const Standard_Boolean dbuff)
51 PIXELFORMATDESCRIPTOR pfd0;
52 memset (&pfd0, 0, sizeof (PIXELFORMATDESCRIPTOR));
53 pfd0.nSize = sizeof (PIXELFORMATDESCRIPTOR);
55 pfd0.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | (dbuff ? PFD_DOUBLEBUFFER : PFD_SUPPORT_GDI);
56 pfd0.iPixelType = PFD_TYPE_RGBA;
57 pfd0.iLayerType = PFD_MAIN_PLANE;
61 const int cBits[] = { 32, 24 };
62 const int dBits[] = { 32, 24, 16 };
65 for (i = 0; i < sizeof(dBits) / sizeof(int); i++)
67 pfd0.cDepthBits = dBits[i];
69 for (j = 0; j < sizeof(cBits) / sizeof(int); j++)
71 pfd0.cColorBits = cBits[j];
72 iPixelFormat = ChoosePixelFormat (hDC, &pfd0);
77 DescribePixelFormat (hDC, iPixelFormat, sizeof (PIXELFORMATDESCRIPTOR), pfd);
78 if (pfd->cColorBits >= cBits[j] && pfd->cDepthBits >= dBits[i])
84 if (j < sizeof(cBits) / sizeof(int))
88 if (iPixelFormat == 0)
94 static Bool WaitForNotify (Display* theDisp, XEvent* theEv, char* theArg)
96 return (theEv->type == MapNotify) && (theEv->xmap.window == (Window )theArg);
102 // =======================================================================
103 // function : OpenGl_Window
105 // =======================================================================
106 OpenGl_Window::OpenGl_Window (const Handle(OpenGl_Display)& theDisplay,
107 const CALL_DEF_WINDOW& theCWindow,
108 Aspect_RenderingContext theGContext)
109 : myDisplay (theDisplay),
111 myGContext ((GLCONTEXT )theGContext),
112 myGlContext (new OpenGl_Context()),
113 myOwnGContext (theGContext == 0),
114 #if (defined(_WIN32) || defined(__WIN32__))
116 mySysPalInUse (FALSE),
118 myWidth ((Standard_Integer )theCWindow.dx),
119 myHeight ((Standard_Integer )theCWindow.dy),
120 myBgColor (THE_DEFAULT_BG_COLOR),
121 myDither (theDisplay->Dither()),
122 myBackDither (theDisplay->BackDither())
124 myBgColor.rgb[0] = theCWindow.Background.r;
125 myBgColor.rgb[1] = theCWindow.Background.g;
126 myBgColor.rgb[2] = theCWindow.Background.b;
128 WINDOW aParent = (WINDOW )theCWindow.XWindow;
129 DISPLAY* aDisp = (DISPLAY* )myDisplay->GetDisplay();
131 #if (!defined(_WIN32) && !defined(__WIN32__))
132 XWindowAttributes wattr;
133 XGetWindowAttributes (aDisp, aParent, &wattr);
134 const int scr = DefaultScreen (aDisp);
136 XVisualInfo* aVis = NULL;
138 unsigned long aVisInfoMask = VisualIDMask | VisualScreenMask;
139 XVisualInfo aVisInfo;
140 aVisInfo.visualid = wattr.visual->visualid;
141 aVisInfo.screen = scr;
143 aVis = XGetVisualInfo (aDisp, aVisInfoMask, &aVisInfo, &aNbItems);
152 Aspect_GraphicDeviceDefinitionError::Raise ("OpenGl_Window::CreateWindow: XGetVisualInfo failed.");
162 #if defined(__linux) || defined(Linux)
165 // check Visual for OpenGl context's parameters compability
166 int isGl = 0, isDoubleBuffer = 0, isRGBA = 0, aDepthSize = 0;
168 if (glXGetConfig (aDisp, aVis, GLX_USE_GL, &isGl) != 0)
171 if (glXGetConfig (aDisp, aVis, GLX_RGBA, &isRGBA) != 0)
174 if (glXGetConfig (aDisp, aVis, GLX_DOUBLEBUFFER, &isDoubleBuffer) != 0)
177 if (glXGetConfig (aDisp, aVis, GLX_DEPTH_SIZE, &aDepthSize) != 0)
180 if (!isGl || !aDepthSize || !isRGBA || (isDoubleBuffer ? 1 : 0) != (myDisplay->DBuffer()? 1 : 0))
192 anAttribs[anIter++] = GLX_RGBA;
194 anAttribs[anIter++] = GLX_DEPTH_SIZE;
195 anAttribs[anIter++] = 1;
197 anAttribs[anIter++] = GLX_RED_SIZE;
198 anAttribs[anIter++] = (wattr.depth <= 8) ? 0 : 1;
200 anAttribs[anIter++] = GLX_GREEN_SIZE;
201 anAttribs[anIter++] = (wattr.depth <= 8) ? 0 : 1;
203 anAttribs[anIter++] = GLX_BLUE_SIZE;
204 anAttribs[anIter++] = (wattr.depth <= 8) ? 0 : 1;
206 if (myDisplay->DBuffer())
207 anAttribs[anIter++] = GLX_DOUBLEBUFFER;
209 anAttribs[anIter++] = None;
211 aVis = glXChooseVisual (aDisp, scr, anAttribs);
214 Aspect_GraphicDeviceDefinitionError::Raise ("OpenGl_Window::CreateWindow: glXChooseVisual failed.");
221 // recover display lists from TheDeadGlxCtx, then destroy it
222 ctx = glXCreateContext (aDisp, aVis, TheDeadGlxCtx, GL_TRUE);
224 OpenGl_ResourceCleaner::GetInstance()->RemoveContext (TheDeadGlxCtx);
225 glXDestroyContext (TheDeadGlxDpy, TheDeadGlxCtx);
229 else if (ThePreviousCtx == 0)
231 ctx = glXCreateContext (aDisp, aVis, NULL, GL_TRUE);
235 // ctx est une copie du previous
236 ctx = glXCreateContext (aDisp, aVis, ThePreviousCtx, GL_TRUE);
241 Aspect_GraphicDeviceDefinitionError::Raise ("OpenGl_Window::CreateWindow: glXCreateContext failed.");
245 OpenGl_ResourceCleaner::GetInstance()->AppendContext (ctx, true);
247 ThePreviousCtx = ctx;
249 Colormap cmap = XCreateColormap (aDisp, aParent, aVis->visual, AllocNone);
252 color.red = (unsigned short) (myBgColor.rgb[0] * 0xFFFF);
253 color.green = (unsigned short) (myBgColor.rgb[1] * 0xFFFF);
254 color.blue = (unsigned short) (myBgColor.rgb[2] * 0xFFFF);
255 color.flags = DoRed | DoGreen | DoBlue;
256 XAllocColor (aDisp, cmap, &color);
258 XSetWindowAttributes cwa;
260 cwa.event_mask = StructureNotifyMask;
261 cwa.border_pixel = color.pixel;
262 cwa.background_pixel = color.pixel;
264 if (aVis->visualid == wattr.visual->visualid)
270 unsigned long mask = CWBackPixel | CWColormap | CWBorderPixel | CWEventMask;
271 win = XCreateWindow (aDisp, aParent, 0, 0, myWidth, myHeight, 0/*bw*/, aVis->depth, InputOutput, aVis->visual, mask, &cwa);
274 XSetWindowBackground (aDisp, win, cwa.background_pixel);
275 XClearWindow (aDisp, win);
280 XMapWindow (aDisp, win);
281 XIfEvent (aDisp, &anEvent, WaitForNotify, (char* )win);
288 * Le BackDitherProp est utilise pour le clear du background
289 * Pour eviter une difference de couleurs avec la couleur choisie
290 * par l'application (XWindow) il faut desactiver le dithering
291 * au dessus de 8 plans.
293 * Pour le DitherProp:
294 * On cherchera a activer le Dithering que si le Visual a au moins
295 * 8 plans pour le GLX_RED_SIZE. Le test est plus sur car on peut
296 * avoir une profondeur superieure a 12 mais avoir besoin du dithering.
297 * (Carte Impact avec GLX_RED_SIZE a 5 par exemple)
301 glXGetConfig (aDisp, aVis, GLX_RED_SIZE, &value);
304 myDither = (value < 8);
307 myBackDither = (aVis->depth <= 8);
309 XFree ((char* )aVis);
315 myWindowDC = GetDC (aParent);
317 PIXELFORMATDESCRIPTOR pfd;
318 int iPixelFormat = find_pixel_format (myWindowDC, &pfd, myDisplay->DBuffer());
319 if (iPixelFormat == 0)
321 ReleaseDC (aParent, myWindowDC);
324 TCollection_AsciiString msg ("OpenGl_Window::CreateWindow: ChoosePixelFormat failed. Error code: ");
325 msg += (int )GetLastError();
326 Aspect_GraphicDeviceDefinitionError::Raise (msg.ToCString());
330 if (pfd.dwFlags & PFD_NEED_PALETTE)
332 WINDOW_DATA* wd = (WINDOW_DATA* )GetWindowLongPtr (aParent, GWLP_USERDATA);
334 mySysPalInUse = (pfd.dwFlags & PFD_NEED_SYSTEM_PALETTE) ? TRUE : FALSE;
335 InterfaceGraphic_RealizePalette (myWindowDC, wd->hPal, FALSE, mySysPalInUse);
339 myDither = (pfd.cColorBits <= 8);
342 myBackDither = (pfd.cColorBits <= 8);
344 if (!SetPixelFormat (myWindowDC, iPixelFormat, &pfd))
346 ReleaseDC (aParent, myWindowDC);
349 TCollection_AsciiString msg("OpenGl_Window::CreateWindow: SetPixelFormat failed. Error code: ");
350 msg += (int)GetLastError();
351 Aspect_GraphicDeviceDefinitionError::Raise (msg.ToCString());
357 ThePreviousCtx = myGContext;
361 myGContext = wglCreateContext (myWindowDC);
362 if (myGContext == NULL)
364 ReleaseDC (aParent, myWindowDC);
367 TCollection_AsciiString msg ("OpenGl_Window::CreateWindow: wglCreateContext failed. Error code: ");
368 msg += (int )GetLastError();
369 Aspect_GraphicDeviceDefinitionError::Raise (msg.ToCString());
373 Standard_Boolean isShared = Standard_True;
374 if (ThePreviousCtx == NULL)
376 ThePreviousCtx = myGContext;
380 // if we already have some shared context
381 GLCONTEXT shareCtx = OpenGl_ResourceCleaner::GetInstance()->GetSharedContext();
382 if (shareCtx != NULL)
384 // try to share context with one from resource cleaner list
385 isShared = (Standard_Boolean )wglShareLists (shareCtx, myGContext);
389 isShared = (Standard_Boolean )wglShareLists (ThePreviousCtx, myGContext);
390 // add shared ThePreviousCtx to a control list if it's not there
392 OpenGl_ResourceCleaner::GetInstance()->AppendContext (ThePreviousCtx, isShared);
396 // add the context to OpenGl_ResourceCleaner control list
397 OpenGl_ResourceCleaner::GetInstance()->AppendContext (myGContext, isShared);
403 #if (defined(_WIN32) || defined(__WIN32__))
404 myGlContext->Init (myWindow, myWindowDC, myGContext);
406 myGlContext->Init (myWindow, myDisplay->GetDisplay(), myGContext);
411 // =======================================================================
412 // function : ~OpenGl_Window
414 // =======================================================================
415 OpenGl_Window::~OpenGl_Window()
417 DISPLAY* aDisp = (DISPLAY* )myDisplay->GetDisplay();
418 if (aDisp == NULL || !myOwnGContext)
421 #if (defined(_WIN32) || defined(__WIN32__))
422 OpenGl_ResourceCleaner::GetInstance()->RemoveContext (myGContext);
424 if (wglGetCurrentContext() != NULL)
425 wglDeleteContext (myGContext);
426 ReleaseDC (myWindow, myWindowDC);
428 if (myDisplay->myMapOfWindows.Size() == 0)
431 // FSXXX sync necessary if non-direct rendering
434 if (ThePreviousCtx == myGContext)
436 ThePreviousCtx = NULL;
437 if (myDisplay->myMapOfWindows.Size() > 0)
439 NCollection_DataMap<Standard_Integer, Handle(OpenGl_Window)>::Iterator it (myDisplay->myMapOfWindows);
440 ThePreviousCtx = it.Value()->myGContext;
443 // if this is the last remaining context, do not destroy it yet, to avoid
444 // losing any shared display lists (fonts...)
447 OpenGl_ResourceCleaner::GetInstance()->RemoveContext(myGContext);
448 glXDestroyContext(aDisp, myGContext);
452 TheDeadGlxCtx = myGContext;
453 TheDeadGlxDpy = aDisp;
458 OpenGl_ResourceCleaner::GetInstance()->RemoveContext (myGContext);
459 glXDestroyContext (aDisp, myGContext);
464 // =======================================================================
465 // function : Activate
467 // =======================================================================
468 Standard_Boolean OpenGl_Window::Activate()
470 return myGlContext->MakeCurrent();
473 // =======================================================================
475 // purpose : call_subr_resize
476 // =======================================================================
477 void OpenGl_Window::Resize (const CALL_DEF_WINDOW& theCWindow)
479 DISPLAY* aDisp = (DISPLAY* )myDisplay->GetDisplay();
483 // If the size is not changed - do nothing
484 if ((myWidth == theCWindow.dx) && (myHeight == theCWindow.dy))
487 myWidth = (Standard_Integer )theCWindow.dx;
488 myHeight = (Standard_Integer )theCWindow.dy;
490 #if (!defined(_WIN32) && !defined(__WIN32__))
491 XResizeWindow (aDisp, myWindow, (unsigned int )myWidth, (unsigned int )myHeight);
492 XSync (aDisp, False);
498 // =======================================================================
499 // function : ReadDepths
500 // purpose : TelReadDepths
501 // =======================================================================
502 void OpenGl_Window::ReadDepths (const Standard_Integer theX, const Standard_Integer theY,
503 const Standard_Integer theWidth, const Standard_Integer theHeight,
506 if (theDepths == NULL || !Activate())
509 glMatrixMode (GL_PROJECTION);
511 gluOrtho2D (0.0, (GLdouble )myWidth, 0.0, (GLdouble )myHeight);
512 glMatrixMode (GL_MODELVIEW);
515 glRasterPos2i (theX, theY);
517 glReadPixels (theX, theY, theWidth, theHeight, GL_DEPTH_COMPONENT, GL_FLOAT, theDepths);
521 // =======================================================================
522 // function : SetBackgroundColor
523 // purpose : call_subr_set_background
524 // =======================================================================
525 void OpenGl_Window::SetBackgroundColor (const Standard_ShortReal theR,
526 const Standard_ShortReal theG,
527 const Standard_ShortReal theB)
529 myBgColor.rgb[0] = theR;
530 myBgColor.rgb[1] = theG;
531 myBgColor.rgb[2] = theB;
534 // =======================================================================
537 // =======================================================================
538 void OpenGl_Window::Init()
543 #if (defined(_WIN32) || defined(__WIN32__))
545 GetClientRect (myWindow, &cr);
546 myWidth = cr.right - cr.left;
547 myHeight = cr.bottom - cr.top;
551 unsigned int aDummyU;
552 unsigned int aNewWidth = 0;
553 unsigned int aNewHeight = 0;
554 DISPLAY* aDisp = (DISPLAY* )myDisplay->GetDisplay();
555 XGetGeometry (aDisp, myWindow, &aRootWin, &aDummy, &aDummy, &aNewWidth, &aNewHeight, &aDummyU, &aDummyU);
557 myHeight = aNewHeight;
560 glMatrixMode (GL_MODELVIEW);
561 glViewport (0, 0, myWidth, myHeight);
563 glDisable (GL_SCISSOR_TEST);
564 glDrawBuffer (GL_BACK);
567 // =======================================================================
568 // function : EnablePolygonOffset
569 // purpose : call_subr_enable_polygon_offset
570 // =======================================================================
571 void OpenGl_Window::EnablePolygonOffset() const
573 Standard_ShortReal aFactor, aUnits;
574 myDisplay->PolygonOffset (aFactor, aUnits);
575 glPolygonOffset (aFactor, aUnits);
576 glEnable (GL_POLYGON_OFFSET_FILL);
579 // =======================================================================
580 // function : DisablePolygonOffset
581 // purpose : call_subr_disable_polygon_offset
582 // =======================================================================
583 void OpenGl_Window::DisablePolygonOffset() const
585 glDisable (GL_POLYGON_OFFSET_FILL);
588 // =======================================================================
589 // function : EnableFeatures
591 // =======================================================================
592 void OpenGl_Window::EnableFeatures() const
594 /*glPixelTransferi (GL_MAP_COLOR, GL_TRUE);*/
597 glEnable (GL_DITHER);
599 glDisable (GL_DITHER);
602 // =======================================================================
603 // function : DisableFeatures
605 // =======================================================================
606 void OpenGl_Window::DisableFeatures() const
608 glDisable (GL_DITHER);
609 glPixelTransferi (GL_MAP_COLOR, GL_FALSE);
612 * Disable stuff that's likely to slow down glDrawPixels.
613 * (Omit as much of this as possible, when you know in advance
614 * that the OpenGL state will already be set correctly.)
616 glDisable(GL_ALPHA_TEST);
618 glDisable(GL_DEPTH_TEST);
620 glDisable(GL_LIGHTING);
622 glDisable(GL_LOGIC_OP);
623 glDisable(GL_STENCIL_TEST);
624 glDisable(GL_TEXTURE_1D);
625 glDisable(GL_TEXTURE_2D);
626 glPixelTransferi(GL_MAP_COLOR, GL_FALSE);
627 glPixelTransferi(GL_RED_SCALE, 1);
628 glPixelTransferi(GL_RED_BIAS, 0);
629 glPixelTransferi(GL_GREEN_SCALE, 1);
630 glPixelTransferi(GL_GREEN_BIAS, 0);
631 glPixelTransferi(GL_BLUE_SCALE, 1);
632 glPixelTransferi(GL_BLUE_BIAS, 0);
633 glPixelTransferi(GL_ALPHA_SCALE, 1);
634 glPixelTransferi(GL_ALPHA_BIAS, 0);
637 * Disable extensions that could slow down glDrawPixels.
638 * (Actually, you should check for the presence of the proper
639 * extension before making these calls. I've omitted that
640 * code for simplicity.)
643 #ifdef GL_EXT_convolution
644 glDisable(GL_CONVOLUTION_1D_EXT);
645 glDisable(GL_CONVOLUTION_2D_EXT);
646 glDisable(GL_SEPARABLE_2D_EXT);
649 #ifdef GL_EXT_histogram
650 glDisable(GL_HISTOGRAM_EXT);
651 glDisable(GL_MINMAX_EXT);
654 #ifdef GL_EXT_texture3D
655 glDisable(GL_TEXTURE_3D_EXT);
659 // =======================================================================
660 // function : MakeFrontBufCurrent
661 // purpose : TelMakeFrontBufCurrent
662 // =======================================================================
663 void OpenGl_Window::MakeFrontBufCurrent() const
665 glDrawBuffer (GL_FRONT);
668 // =======================================================================
669 // function : MakeBackBufCurrent
670 // purpose : TelMakeBackBufCurrent
671 // =======================================================================
672 void OpenGl_Window::MakeBackBufCurrent() const
674 glDrawBuffer (GL_BACK);
677 // =======================================================================
678 // function : MakeFrontAndBackBufCurrent
679 // purpose : TelMakeFrontAndBackBufCurrent
680 // =======================================================================
681 void OpenGl_Window::MakeFrontAndBackBufCurrent() const
683 glDrawBuffer (GL_FRONT_AND_BACK);