void windowResize(GLWindow *glw, uint32 newH, uint32 newW)
{
    glw->winH = newH;
    glw->winW = newW;
    aglSetCurrentContext(glw->glCtx);
    aglSetDrawable(glw->glCtx, NULL);
    aglSetDrawable(glw->glCtx, GetWindowPort(glw->pWin));
}
Exemplo n.º 2
0
void _glfwPlatformCloseWindow( void )
{
    if( _glfwWin.WindowFunctions != NULL )
    {
	    if( _glfwWin.WindowUPP != NULL )
	    {
	        DisposeEventHandlerUPP( _glfwWin.WindowUPP );
	        _glfwWin.WindowUPP = NULL;
	    }

	    _glfwWin.WindowFunctions->CloseWindow();

	    if( _glfwWin.AGLContext != NULL )
	    {
		    aglSetCurrentContext( NULL );
		    aglSetDrawable( _glfwWin.AGLContext, NULL );
		    aglDestroyContext( _glfwWin.AGLContext );
		    _glfwWin.AGLContext = NULL;
		}

    	if( _glfwWin.MacWindow != NULL )
    	{
		    ReleaseWindow( _glfwWin.MacWindow );
		    _glfwWin.MacWindow = NULL;
	    }

	    _glfwWin.WindowFunctions = NULL;
    }
}
Exemplo n.º 3
0
bool AquaOglGlue::prepDrawingArea(int width, int height, AGLDrawable drawable)
{
    GNASH_REPORT_FUNCTION;
    bool ret = aglSetDrawable(_context, drawable);

    return ret;
}
Exemplo n.º 4
0
bool wxGLContext::SetCurrent(const wxGLCanvas& win) const
{
    if ( !m_glContext )
        return false;

    AGLDrawable drawable = (AGLDrawable)GetWindowPort(
                                MAC_WXHWND(win.MacGetTopLevelWindowRef()));

    GLint bufnummer = win.GetAglBufferName();
    aglSetInteger(m_glContext, AGL_BUFFER_NAME, &bufnummer);
    //win.SetLastContext(m_glContext);
    
    const_cast<wxGLCanvas&>(win).SetViewport();

    if ( !aglSetDrawable(m_glContext, drawable) )
    {
        wxLogAGLError("aglSetDrawable");
        return false;
    }

    if ( !aglSetCurrentContext(m_glContext) )
    {
        wxLogAGLError("aglSetCurrentContext");
        return false;
    }
    return true;
}
Exemplo n.º 5
0
bool wxGLCanvas::Create(wxWindow *parent,
                        wxWindowID id,
                        const wxPoint& pos,
                        const wxSize& size,
                        long style,
                        const wxString& name,
                        const int *attribList,
                        const wxPalette& WXUNUSED(palette))
{
    m_needsUpdate = false;
    m_macCanvasIsShown = false;

    m_glFormat = WXGLChoosePixelFormat(attribList);
    if ( !m_glFormat )
        return false;

    if ( !wxWindow::Create(parent, id, pos, size, style, name) )
        return false;

    m_dummyContext = WXGLCreateContext(m_glFormat, NULL);

    static GLint gCurrentBufferName = 1;
    m_bufferName = gCurrentBufferName++;
    aglSetInteger (m_dummyContext, AGL_BUFFER_NAME, &m_bufferName); 
    
    AGLDrawable drawable = (AGLDrawable)GetWindowPort(MAC_WXHWND(MacGetTopLevelWindowRef()));
    aglSetDrawable(m_dummyContext, drawable);

    m_macCanvasIsShown = true;

    return true;
}
Exemplo n.º 6
0
bool wxGLContext::SetCurrent(const wxGLCanvas& win) const
{
    if ( !m_glContext )
        return false;

    GLint bufnummer = win.GetAglBufferName();
    aglSetInteger(m_glContext, AGL_BUFFER_NAME, &bufnummer);
    //win.SetLastContext(m_glContext);

    const_cast<wxGLCanvas&>(win).SetViewport();

    
#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
    if ( UMAGetSystemVersion() >= 0x1050 )
    {
        aglSetWindowRef(m_glContext, win.MacGetTopLevelWindowRef());
    }
    else
#endif
    {
        AGLDrawable drawable = (AGLDrawable)GetWindowPort(
                                                      MAC_WXHWND(win.MacGetTopLevelWindowRef()));
    
        if ( !aglSetDrawable(m_glContext, drawable) )
        {
            wxLogAGLError("aglSetDrawable");
            return false;
        }
    }

    return WXGLSetCurrentContext(m_glContext);
}
Exemplo n.º 7
0
wxGLContext::wxGLContext(
                         AGLPixelFormat fmt, wxGLCanvas *win,
                         const wxPalette& palette,
                         const wxGLContext *other        /* for sharing display lists */
                         )
{
    m_window = win;
#ifndef __LP64__
    m_drawable = (AGLDrawable) UMAGetWindowPort(MAC_WXHWND(win->MacGetTopLevelWindowRef()));
#endif

    m_glContext = aglCreateContext(fmt, other ? other->m_glContext : NULL);
    wxCHECK_RET( m_glContext, wxT("Couldn't create OpenGl context") );

    GLboolean b;
#ifndef __LP64__
    b = aglSetDrawable(m_glContext, m_drawable);
    aglEnable(m_glContext , AGL_BUFFER_RECT ) ;
#else
    b = aglSetHIViewRef(m_glContext, (HIViewRef) win->GetHandle());
#endif
    wxCHECK_RET( b, wxT("Couldn't bind OpenGl context") );
    b = aglSetCurrentContext(m_glContext);
    wxCHECK_RET( b, wxT("Couldn't activate OpenGl context") );
}
Exemplo n.º 8
0
static void RLXAPI ReleaseSurfaces(void)
{
	if (!g_pAGLC)
		return;

	aglSetCurrentContext(NULL);
    aglSetDrawable(g_pAGLC, NULL);
    aglDestroyContext(g_pAGLC);
    g_pAGLC = 0;
	g_pRLX->pGX->Surfaces.maxSurface = 0;
}
Exemplo n.º 9
0
void Mac_GL_Quit(_THIS)
{
#ifdef HAVE_OPENGL
	if ( glContext != NULL ) {
		aglSetCurrentContext(NULL);
		aglSetDrawable(glContext, NULL);
		aglDestroyContext(glContext);		
		glContext = NULL;
	}
#endif
}
Exemplo n.º 10
0
void OpenGLApp::exitAPI(){
	delete renderer;
	
	aglSetCurrentContext(NULL);
	aglSetDrawable(glContext, NULL);
	aglDestroyContext(glContext);
	ReleaseWindow(window);

	if (fullscreen){
		CGReleaseAllDisplays();
		CGDisplaySwitchToMode(kCGDirectMainDisplay, initialMode);
	}
}
static void
_glitz_agl_context_make_current (glitz_agl_drawable_t *drawable,
				 glitz_bool_t         finish)
{
    if (finish)
	glFinish ();

    if (drawable->thread_info->cctx)
    {
	glitz_context_t *ctx = drawable->thread_info->cctx;

	if (ctx->lose_current)
	    ctx->lose_current (ctx->closure);

	drawable->thread_info->cctx = NULL;
    }

    if (drawable->pbuffer) {
	aglSetPBuffer (drawable->context->context, drawable->pbuffer, 0, 0,
		       aglGetVirtualScreen (drawable->context->context));
	drawable->context->pbuffer = 1;
    } else {
	if (drawable->context->pbuffer) {
	    aglSetDrawable (drawable->context->context, NULL);
	    drawable->context->pbuffer = 0;
	}

	aglSetDrawable (drawable->context->context, drawable->drawable);
    }

    aglSetCurrentContext (drawable->context->context);

    drawable->base.update_all = 1;

    if (!drawable->context->initialized)
	_glitz_agl_context_initialize (drawable->thread_info,
				       drawable->context);
}
Exemplo n.º 12
0
void
GelatinePaneView::dispose()
{
  _model.getSpace().getView().dispose();

  aglSetCurrentContext(NULL);
  aglSetDrawable(_model._aglContext, NULL);

  aglDestroyContext(_model._aglContext);
  aglDestroyPixelFormat(_model._aglPixelFormat);

  _model._aglContext = NULL;
  _model._aglPixelFormat = NULL;
}
Exemplo n.º 13
0
bool nglContext::MakeCurrent(WindowRef win) const
{
  bool res = true;
#ifndef __NOGLCONTEXT__
  if (mCtx)
    res = aglSetCurrentContext(mCtx) != 0;
  if (win)
    aglSetDrawable(mCtx, GetWindowPort(win));
  
  CGLContextObj ctx = CGLGetCurrentContext();
  CGLPixelFormatObj pixelFormat = CGLGetPixelFormat(ctx);
  //printf("cglcontext  : 0x%x / 0x%x\n", ctx, pixelFormat);
#endif
  return res;
}
Exemplo n.º 14
0
void
GelatinePaneView::swapPortsAndDisplay()
{
  GrafPtr savedPort;
  GetPort(&savedPort);
  SetPort(GetWindowPort(_model._windowRef));
  aglSetDrawable(_model._aglContext, GetWindowPort(_model._windowRef));
  aglSetCurrentContext(_model._aglContext);
  display();

    Rect portRect;
    GetWindowPortBounds(getModel().getWindowRef(), &portRect);
    InvalWindowRect(getModel().getWindowRef(), &portRect);
  
  SetPort(savedPort);
}
Exemplo n.º 15
0
void Shell::CloseWindow()
{
	// Shutdown OpenGL if necessary.
	if (opengl_attached)
	{
		aglSetCurrentContext(NULL);
		aglSetDrawable(gl_context, NULL);
		aglDestroyContext(gl_context);
		
		gl_context = NULL;
	}

	// Close the window.
	HideWindow(window);
	ReleaseWindow(window);
}
Exemplo n.º 16
0
bool
WindowSystem::makeCurrent(RenderingContext& r, Window& w) {
#   if defined(__X11__)
#	if defined(GLX_VERSION_1_3)
	    // XXX Need to write GLX 1.3 MakeCurrent code
#	endif
	    return glXMakeCurrent(dpy, w.xWindow, r.rc);
#   elif defined(__WIN__)
		return wglMakeCurrent(w.get_dc(),r.rc);
#   elif defined(__AGL__)
		if (GL_FALSE == aglSetDrawable(r.rc, (AGLDrawable) GetWindowPort (w.macWindow)))
			return GL_FALSE;
		if (GL_FALSE == aglSetCurrentContext(r.rc))
			return GL_FALSE;
		return true;
#   endif
} // WindowSystem::makeCurrent
Exemplo n.º 17
0
// ---------------------------------------------------------------------------
void OSXWindowImpl::init_gl()
{
  GLint attributes[] = {
    AGL_RGBA,
    AGL_DOUBLEBUFFER,
    AGL_LEVEL, 1,
    AGL_WINDOW, GL_TRUE,
    AGL_DEPTH_SIZE, 1,
    AGL_NONE
  };
  AGLPixelFormat pf = aglChoosePixelFormat(NULL,0,attributes);
  assert(pf);
  mGLContext = aglCreateContext( pf, NULL );
  assert(mGLContext);
  GLboolean b = aglSetDrawable( mGLContext, GetWindowPort(mWindowRef) );
  assert(b);
  aglSetCurrentContext(mGLContext);
}
Exemplo n.º 18
0
static void HIOpenGLViewSetContextWindowAndBounds (HIOpenGLViewData* inData)
{
    if (inData == nil) return;
    if (inData->mControl == nil) return;
    if (inData->mContext == nil) return;

    // Determine the AGL_BUFFER_RECT for the control. The coordinate
    // system for this rectangle is relative to the owning window, with
    // the origin at the bottom left corner and the y-axis inverted.
    HIRect ctrlBounds, winBounds;
    HIViewGetBounds(inData->mControl, &ctrlBounds);
    WindowRef window = GetControlOwner(inData->mControl);
    ControlRef root = nil;
    GetRootControl(window, &root);
    HIViewGetBounds(root, &winBounds);
    HIViewConvertRect(&ctrlBounds, inData->mControl, root);
    GLint bufferRect[4] = { (int)ctrlBounds.origin.x, (int)((winBounds.size.height) - (ctrlBounds.origin.y + ctrlBounds.size.height)),
                            (int)ctrlBounds.size.width, (int)ctrlBounds.size.height };
    
    // Associate the OpenGL context with the control's window, and establish the buffer rect.
    aglSetDrawable(inData->mContext, GetWindowPort(window));
    aglSetInteger(inData->mContext, AGL_BUFFER_RECT, bufferRect);
    aglEnable(inData->mContext, AGL_BUFFER_RECT);
    
    // Establish the clipping region for the OpenGL context. To properly handle clipping
    // within the view hierarchy, I'm walking the hierarchy to determine the intersection
    // of this view's bounds with its parents. Is there an easier way to do this?
    CGRect clipBounds = ctrlBounds;
    HIViewRef parent = HIViewGetSuperview(inData->mControl);
    while (parent != root)
    {
        CGRect parentBounds;
        HIViewGetBounds(parent, &parentBounds);
        HIViewConvertRect(&parentBounds, parent, root);
        clipBounds = CGRectIntersection(clipBounds, parentBounds);
        parent = HIViewGetSuperview(parent);
    }
    Rect rgnBounds = { (int)clipBounds.origin.y, (int)clipBounds.origin.x, (int)(clipBounds.origin.y + clipBounds.size.height), (int)(clipBounds.origin.x + clipBounds.size.width) };
    RgnHandle rgn = NewRgn();
    RectRgn(rgn, &rgnBounds);
    
    aglSetInteger(inData->mContext, AGL_CLIP_REGION, (const GLint*)rgn);
    aglEnable(inData->mContext, AGL_CLIP_REGION);
}
Exemplo n.º 19
0
wxGLContext::wxGLContext(
                         AGLPixelFormat fmt, wxGLCanvas *win,
                         const wxPalette& palette,
                         const wxGLContext *other        /* for sharing display lists */
                         )
{
    m_window = win;
    
    m_drawable = (AGLDrawable) UMAGetWindowPort(MAC_WXHWND(win->MacGetRootWindow()));
    
    m_glContext = aglCreateContext(fmt, other ? other->m_glContext : NULL);
    wxCHECK_RET( m_glContext, wxT("Couldn't create OpenGl context") );
    
    GLboolean b;
    b = aglSetDrawable(m_glContext, m_drawable);
    wxCHECK_RET( b, wxT("Couldn't bind OpenGl context") );
    aglEnable(m_glContext , AGL_BUFFER_RECT ) ;
    b = aglSetCurrentContext(m_glContext);
    wxCHECK_RET( b, wxT("Couldn't activate OpenGl context") );
}
Exemplo n.º 20
0
void windowDestroy(GLWindow *glw)
{
	MenuHandle hMenu;
	aglSetDrawable(glw->glCtx, NULL);
	aglSetCurrentContext(NULL);
	aglDestroyContext(glw->glCtx);
	
	DisposeWindow((WindowPtr)glw->pWin);
	glw->pWin = NULL;
	if(glw->supportWindow)
	    DisposeWindow((WindowPtr)glw->supportWindow);
	hMenu = GetMenuHandle (kMenuFile);
	DeleteMenu (kMenuFile);
	DisposeMenu (hMenu);

	hMenu = GetMenuHandle (kMenuApple);
	DeleteMenu (kMenuApple);
	DisposeMenu (hMenu);

}
void CL_DisplayWindow_OpenGL::set_windowed()
{
	if(!fullscreen)
		return;

	if (context == fs_context)
	{
	    aglSetDrawable(fs_context, 0);
	}
	
	CGReleaseAllDisplays();
	aglSetCurrentContext(win_context);
	aglUpdateContext(win_context);
	install_event_handler(GetWindowEventTarget(window_ref));

	fullscreen = false;
	context = win_context;
	focus = IsWindowHilited(window_ref);
	
	//After toggling to the fullscreen context, nothing is going draw unless
	//we reapply the GL states/properties -mrfun 6-2-2006
	CL_GLStateChecker::from_gc(get_gc())->reinitialize_asap();
	
}
Exemplo n.º 22
0
bool OpenGLApp::initAPI(){
	initialMode = CGDisplayCurrentMode(kCGDirectMainDisplay);

	dmodes = CGDisplayAvailableModes(kCGDirectMainDisplay);
	int count = CFArrayGetCount(dmodes);

	Array <DispRes> modes;
	int foundMode = -1;
	for (int i = 0; i < count; i++){
		CFDictionaryRef mode = (CFDictionaryRef) CFArrayGetValueAtIndex(dmodes, i);

		long bitsPerPixel = GetDictionaryLong(mode, kCGDisplayBitsPerPixel);
		Boolean safeForHardware = GetDictionaryBoolean(mode, kCGDisplayModeIsSafeForHardware);
		Boolean stretched = GetDictionaryBoolean(mode, kCGDisplayModeIsStretched);

		if (bitsPerPixel < colorBits || !safeForHardware || stretched) continue;

		long width  = GetDictionaryLong(mode, kCGDisplayWidth);
		long height = GetDictionaryLong(mode, kCGDisplayHeight);
		long refreshRate = GetDictionaryLong(mode, kCGDisplayRefreshRate);

//		printf("Mode: %dx%dx%d @ %d\n", width, height, bitsPerPixel, refreshRate);

		if (width >= 640 && height >= 480){
			modes.add(newRes(width, height, i));

			if (width == fullscreenWidth && height == fullscreenHeight){
				foundMode = i;
			}
		}
	}

	resolution->clear();
	modes.sort(dComp);
	char str[64];
	for (uint i = 0; i < modes.getCount(); i++){
		sprintf(str, "%dx%d", modes[i].w, modes[i].h);
		int index = resolution->addItemUnique(str);
		if (modes[i].index == foundMode) resolution->selectItem(index);
	}

	if (fullscreen){
		if (foundMode < 0 || CGDisplaySwitchToMode(kCGDirectMainDisplay, (CFDictionaryRef) CFArrayGetValueAtIndex(dmodes, foundMode)) != kCGErrorSuccess){
			sprintf(str, "Couldn't set fullscreen to %dx%d.", fullscreenWidth, fullscreenHeight);
			ErrorMsg(str);
			fullscreen = false;
		}
	}


	Rect rect;
	if (fullscreen){
		rect.left = 0;
		rect.top  = 0;
	} else {
		long w = GetDictionaryLong(initialMode, kCGDisplayWidth);
		long h = GetDictionaryLong(initialMode, kCGDisplayHeight);

		rect.left = (w - width) / 2;
		rect.top  = (h - height) / 2;
	}
	rect.right = rect.left + width;
	rect.bottom = rect.top + height;

	WindowAttributes attributes = fullscreen? (kWindowNoTitleBarAttribute | kWindowNoShadowAttribute) : (kWindowStandardDocumentAttributes | kWindowStandardHandlerAttribute);

	OSStatus error = CreateNewWindow(kDocumentWindowClass, attributes, &rect, &window);
	if (error != noErr || window == NULL){
		ErrorMsg("Couldn't create window");
		return false;
	}

    GDHandle screen = GetGWorldDevice(GetWindowPort(window));
    if (screen == NULL){
        ErrorMsg("Couldn't get device");
        ReleaseWindow(window);
        return false;
    }

	AGLPixelFormat pixelFormat;
	while (true){
		GLint attributes[] = {
			fullscreen? AGL_FULLSCREEN : AGL_WINDOW,
			AGL_RGBA,
			AGL_DOUBLEBUFFER,
			AGL_RED_SIZE,            8,
			AGL_GREEN_SIZE,          8,
			AGL_BLUE_SIZE,           8,
			AGL_ALPHA_SIZE,         (colorBits > 24)? 8 : 0,
			AGL_DEPTH_SIZE,          depthBits,
			AGL_STENCIL_SIZE,        stencilBits,
			AGL_SAMPLE_BUFFERS_ARB, (antiAliasSamples > 0),
			AGL_SAMPLES_ARB,         antiAliasSamples,
			AGL_NONE
		};

		pixelFormat = aglChoosePixelFormat(&screen, 1, attributes);
		if (pixelFormat != NULL) break;

		antiAliasSamples -= 2;
		if (antiAliasSamples < 0){
			ErrorMsg("No suitable pixel format");
			ReleaseWindow(window);
			return false;
		}
	}

	glContext = aglCreateContext(pixelFormat, NULL);
    aglDestroyPixelFormat(pixelFormat);

	if (glContext == NULL){
		ErrorMsg("Couldn't create context");
		ReleaseWindow(window);
		return false;
	}

	if (fullscreen){
		CGCaptureAllDisplays();
		aglSetFullScreen(glContext, 0, 0, 0, 0);
	} else {
		if (!aglSetDrawable(glContext, GetWindowPort(window))){
			ErrorMsg("Couldn't set drawable");
			aglDestroyContext(glContext);
			ReleaseWindow(window);
			return false;
		}
	}

	if (!aglSetCurrentContext(glContext)){
		ErrorMsg("Couldn't make context current");
		aglDestroyContext(glContext);
		ReleaseWindow(window);
		return false;
	}

	setWindowTitle(getTitle());
    ShowWindow(window);

	initExtensions();

	if (antiAliasSamples > 0){
		glEnable(GL_MULTISAMPLE_ARB);
	}

	if (fullscreen) captureMouse(!configDialog->isVisible());

	renderer = new OpenGLRenderer(glContext);
	renderer->setViewport(width, height);

	antiAlias->selectItem(antiAliasSamples / 2);

	linearClamp = renderer->addSamplerState(LINEAR, CLAMP, CLAMP, CLAMP);
	defaultFont = renderer->addFont("../Textures/Fonts/Future.dds", "../Textures/Fonts/Future.font", linearClamp);
	blendSrcAlpha = renderer->addBlendState(SRC_ALPHA, ONE_MINUS_SRC_ALPHA);
	noDepthTest  = renderer->addDepthState(false, false);
	noDepthWrite = renderer->addDepthState(true,  false);
	cullNone  = renderer->addRasterizerState(CULL_NONE);
	cullBack  = renderer->addRasterizerState(CULL_BACK);
	cullFront = renderer->addRasterizerState(CULL_FRONT);

	return true;
}
Exemplo n.º 23
0
//-------------------------------------------------------------------------------------------------//
void OSXCarbonWindow::create( const String& name, unsigned int width, unsigned int height,
	            bool fullScreen, const NameValuePairList *miscParams )
{
	bool hasDepthBuffer;
	String title = name;
	size_t fsaa_samples = 0;
	int left = 0;
	int top = 0;
	int depth = 32;
	
	if( miscParams )
	{
		
		NameValuePairList::const_iterator opt = NULL;
		
		// Full screen anti aliasing
		opt = miscParams->find( "FSAA" );
		if( opt != miscParams->end() )
			fsaa_samples = StringConverter::parseUnsignedInt( opt->second );

		opt = miscParams->find( "left" );
		if( opt != miscParams->end() )
			left = StringConverter::parseUnsignedInt( opt->second );

		opt = miscParams->find( "top" );
		if( opt != miscParams->end() )
			top = StringConverter::parseUnsignedInt( opt->second );

		opt = miscParams->find( "title" );
		if( opt != miscParams->end() )
			title = opt->second;

		opt = miscParams->find( "depthBuffer" );
		if( opt != miscParams->end() )
			hasDepthBuffer = StringConverter::parseBool( opt->second );
		
		opt = miscParams->find( "colourDepth" );
		if( opt != miscParams->end() )
			depth = StringConverter::parseUnsignedInt( opt->second );
	}
	
	if(fullScreen)
	{
		GLRenderSystem *rs = static_cast<GLRenderSystem*>(Root::getSingleton().getRenderSystem());
		OSXContext *mainContext = (OSXContext*)rs->_getMainContext();
		
		CGLContextObj share = NULL;
		if(mainContext == 0)
		{
			share = NULL;
		}
		else if(mainContext->getContextType() == "AGL")
		{
			OSXCarbonContext* aglShare = static_cast<OSXCarbonContext*>(mainContext);
			aglGetCGLContext(aglShare->getContext(), &((void*)share));
		}
		else if(mainContext->getContextType() == "CGL")
		{
			OSXCGLContext* cglShare = static_cast<OSXCGLContext*>(mainContext);
			share = cglShare->getContext();
		}
		
		// create the context
		createCGLFullscreen(width, height, depth, fsaa_samples, share);		
	}
	else
	{
		int i = 0;
		AGLPixelFormat pixelFormat;
		GLint attribs[ 20 ];
		
		attribs[ i++ ] = AGL_NO_RECOVERY;
		attribs[ i++ ] = GL_TRUE;
		attribs[ i++ ] = AGL_ACCELERATED;
		attribs[ i++ ] = GL_TRUE;
		attribs[ i++ ] = AGL_RGBA;
		attribs[ i++ ] = AGL_DOUBLEBUFFER;
		attribs[ i++ ] = AGL_ALPHA_SIZE;
		attribs[ i++ ] = 8;
		attribs[ i++ ] = AGL_STENCIL_SIZE;
		attribs[ i++ ] = 8;
		attribs[ i++ ] = AGL_DEPTH_SIZE;
		attribs[ i++ ] = depth;
	
		if(fsaa_samples > 1)
		{
			attribs[ i++ ] = AGL_MULTISAMPLE;
			attribs[ i++ ] = 1;
			attribs[ i++ ] = AGL_SAMPLE_BUFFERS_ARB;
			attribs[ i++ ] = fsaa_samples;
		}
	
		attribs[ i++ ] = AGL_NONE;
	
		pixelFormat = aglChoosePixelFormat( NULL, 0, attribs );
	
		// Create the AGLContext from our pixel format
		// Share it with main
		GLRenderSystem *rs = static_cast<GLRenderSystem*>(Root::getSingleton().getRenderSystem());
		OSXContext* mainContext = static_cast<OSXContext*>( rs->_getMainContext() );
		if(mainContext == 0)
		{
			mAGLContext = aglCreateContext(pixelFormat, NULL);
		}
		else if(mainContext->getContextType() == "AGL")
		{
			OSXCarbonContext* context = static_cast<OSXCarbonContext*>( rs->_getMainContext() );
			AGLContext shared = context->getContext();
			mAGLContext = aglCreateContext(pixelFormat, context->getContext());
		}
		else
		{
			// If we do not have an AGL, we can not clone it using this window
			LogManager::getSingleton().logMessage( "Warning: You asked to create a second window, "
				"when the previous window was not of this type.  OgreOSXCarbonWindow can only share "
				"with an AGL context.");
		}
		
		NameValuePairList::const_iterator opt = 0;
		if(miscParams)
			opt = miscParams->find("externalWindowHandle");
		if(!miscParams || opt == miscParams->end())
		{
			// create the window rect in global coords
			::Rect windowRect;
			windowRect.left = 0;
			windowRect.top = 0;
			windowRect.right = width;
			windowRect.bottom = height;
			
			// set the default attributes for the window
			WindowAttributes windowAttrs = kWindowStandardDocumentAttributes; // default: "resize"
			
			if (miscParams)
			{
				opt = miscParams->find("border");
				if( opt != miscParams->end() )
				{
					String borderType = opt->second;
					if( borderType == "none" )
						windowAttrs = kWindowNoTitleBarAttribute;
					else if( borderType == "fixed" )
						windowAttrs = kWindowStandardFloatingAttributes;
				}
			}
			
			windowAttrs |= kWindowStandardHandlerAttribute | kWindowInWindowMenuAttribute | kWindowHideOnFullScreenAttribute;
			
			// Create the window
			CreateNewWindow(kDocumentWindowClass, windowAttrs, &windowRect, &mWindow);
			
			// Color the window background black
			SetThemeWindowBackground (mWindow, kThemeBrushBlack, true);
			
			// Set the title of our window
			CFStringRef titleRef = CFStringCreateWithCString( kCFAllocatorDefault, title.c_str(), kCFStringEncodingASCII );
			SetWindowTitleWithCFString( mWindow, titleRef );
			
			// Center our window on the screen
			RepositionWindow( mWindow, NULL, kWindowCenterOnMainScreen );
            
            // Get our view
            HIViewFindByID( HIViewGetRoot( mWindow ), kHIViewWindowContentID, &mView );
			
			// Set up our UPP for Window Events
            EventTypeSpec eventSpecs[] = {
                {kEventClassWindow, kEventWindowActivated},
                {kEventClassWindow, kEventWindowDeactivated},
                {kEventClassWindow, kEventWindowShown},
                {kEventClassWindow, kEventWindowHidden},
                {kEventClassWindow, kEventWindowDragCompleted},
                {kEventClassWindow, kEventWindowBoundsChanged},
                {kEventClassWindow, kEventWindowExpanded},
                {kEventClassWindow, kEventWindowCollapsed},
                {kEventClassWindow, kEventWindowClosed},
                {kEventClassWindow, kEventWindowClose}
            };
            
            EventHandlerUPP handlerUPP = NewEventHandlerUPP(WindowEventUtilities::_CarbonWindowHandler);
            
            // Install the standard event handler for the window
            EventTargetRef target = GetWindowEventTarget(mWindow);
			InstallStandardEventHandler(target);
            
            // We also need to install the WindowEvent Handler, we pass along the window with our requests
            InstallEventHandler(target, handlerUPP, 10, eventSpecs, (void*)this, &mEventHandlerRef);
			
			// Display and select our window
			ShowWindow(mWindow);
			SelectWindow(mWindow);
            
            // Add our window to the window event listener class
            WindowEventUtilities::_addRenderWindow(this);
		}
		else
		{
			// TODO: The Contol is going to report the incorrect location with a
			// Metalic / Textured window.  The default windows work just fine.
			
			// First get the HIViewRef / ControlRef
			mView = (HIViewRef)StringConverter::parseUnsignedLong(opt->second);
			mWindow = GetControlOwner(mView);
			
			// Lets try hiding the HIView
			//HIViewSetVisible(mView, false);
					
			// Get the rect bounds
			::Rect ctrlBounds;
			GetControlBounds(mView, &ctrlBounds);
			GLint bufferRect[4];

			bufferRect[0] = ctrlBounds.left;					// left edge
			bufferRect[1] = ctrlBounds.bottom;					// bottom edge
			bufferRect[2] =	ctrlBounds.right - ctrlBounds.left; // width of buffer rect
			bufferRect[3] = ctrlBounds.bottom - ctrlBounds.top; // height of buffer rect
			aglSetInteger(mAGLContext, AGL_BUFFER_RECT, bufferRect);
			aglEnable (mAGLContext, AGL_BUFFER_RECT);
            
            mIsExternal = true;
		}
		
		// Set the drawable, and current context
		// If you do this last, there is a moment before the rendering window pops-up
		// This could go once inside each case above, before the window is displayed,
		// if desired.
		aglSetDrawable(mAGLContext, GetWindowPort(mWindow));
		aglSetCurrentContext(mAGLContext);

		// Give a copy of our context to the render system
		mContext = new OSXCarbonContext(mAGLContext, pixelFormat);
	}
	
	mName = name;
	mWidth = width;
	mHeight = height;
	mActive = true;
    mClosed = false;
    mCreated = true;
	mIsFullScreen = fullScreen;
}
Exemplo n.º 24
0
int  _glfwPlatformOpenWindow( int width,
                              int height,
                              int redbits,
                              int greenbits,
                              int bluebits,
                              int alphabits,
                              int depthbits,
                              int stencilbits,
                              int mode,
                              _GLFWhints* hints )
{
    OSStatus error;
    ProcessSerialNumber psn;

    unsigned int windowAttributes;

    // TO DO: Refactor this function!
    _glfwWin.WindowFunctions = ( _glfwWin.Fullscreen ?
                               &_glfwMacFSWindowFunctions :
                               &_glfwMacDWWindowFunctions );

    // Windowed or fullscreen; AGL or CGL? Quite the mess...
    // AGL appears to be the only choice for attaching OpenGL contexts to
    // Carbon windows, but it leaves the user no control over fullscreen
    // mode stretching. Solution: AGL for windowed, CGL for fullscreen.
    if( !_glfwWin.Fullscreen )
    {
        // create AGL pixel format attribute list
        GLint AGLpixelFormatAttributes[256];
        int numAGLAttrs = 0;

        AGLpixelFormatAttributes[numAGLAttrs++] = AGL_RGBA;
        AGLpixelFormatAttributes[numAGLAttrs++] = AGL_DOUBLEBUFFER;

        if( hints->Stereo )
        {
            AGLpixelFormatAttributes[numAGLAttrs++] = AGL_STEREO;
        }

        _setAGLAttribute( AGL_AUX_BUFFERS,      hints->AuxBuffers);
        _setAGLAttribute( AGL_RED_SIZE,         redbits );
        _setAGLAttribute( AGL_GREEN_SIZE,       greenbits );
        _setAGLAttribute( AGL_BLUE_SIZE,        bluebits );
        _setAGLAttribute( AGL_ALPHA_SIZE,       alphabits );
        _setAGLAttribute( AGL_DEPTH_SIZE,       depthbits );
        _setAGLAttribute( AGL_STENCIL_SIZE,     stencilbits );
        _setAGLAttribute( AGL_ACCUM_RED_SIZE,   hints->AccumRedBits );
        _setAGLAttribute( AGL_ACCUM_GREEN_SIZE, hints->AccumGreenBits );
        _setAGLAttribute( AGL_ACCUM_BLUE_SIZE,  hints->AccumBlueBits );
        _setAGLAttribute( AGL_ACCUM_ALPHA_SIZE, hints->AccumAlphaBits );

	if( hints->Samples > 1 )
	{
	    _setAGLAttribute( AGL_SAMPLE_BUFFERS_ARB, 1 );
	    _setAGLAttribute( AGL_SAMPLES_ARB, hints->Samples );
	    AGLpixelFormatAttributes[numAGLAttrs++] = AGL_NO_RECOVERY;
	}

        AGLpixelFormatAttributes[numAGLAttrs++] = AGL_NONE;

        // create pixel format descriptor
        AGLDevice mainMonitor = GetMainDevice();
        AGLPixelFormat pixelFormat = aglChoosePixelFormat( &mainMonitor,
                                                           1,
                                                           AGLpixelFormatAttributes );
        if( pixelFormat == NULL )
        {
            fprintf( stderr, "glfwOpenWindow failing because it can't create a pixel format\n" );
            return GL_FALSE;
        }

        // store pixel format's values for _glfwPlatformGetWindowParam's use
        _getAGLAttribute( AGL_ACCELERATED,      _glfwWin.Accelerated );
        _getAGLAttribute( AGL_RED_SIZE,         _glfwWin.RedBits );
        _getAGLAttribute( AGL_GREEN_SIZE,       _glfwWin.GreenBits );
        _getAGLAttribute( AGL_BLUE_SIZE,        _glfwWin.BlueBits );
        _getAGLAttribute( AGL_ALPHA_SIZE,       _glfwWin.AlphaBits );
        _getAGLAttribute( AGL_DEPTH_SIZE,       _glfwWin.DepthBits );
        _getAGLAttribute( AGL_STENCIL_SIZE,     _glfwWin.StencilBits );
        _getAGLAttribute( AGL_ACCUM_RED_SIZE,   _glfwWin.AccumRedBits );
        _getAGLAttribute( AGL_ACCUM_GREEN_SIZE, _glfwWin.AccumGreenBits );
        _getAGLAttribute( AGL_ACCUM_BLUE_SIZE,  _glfwWin.AccumBlueBits );
        _getAGLAttribute( AGL_ACCUM_ALPHA_SIZE, _glfwWin.AccumAlphaBits );
        _getAGLAttribute( AGL_AUX_BUFFERS,      _glfwWin.AuxBuffers );
        _getAGLAttribute( AGL_STEREO,           _glfwWin.Stereo );
        _getAGLAttribute( AGL_SAMPLES_ARB,      _glfwWin.Samples );
        _glfwWin.RefreshRate = hints->RefreshRate;

        // create AGL context
        _glfwWin.AGLContext = aglCreateContext( pixelFormat, NULL );

        aglDestroyPixelFormat( pixelFormat );

        if( _glfwWin.AGLContext == NULL )
        {
            fprintf( stderr, "glfwOpenWindow failing because it can't create an OpenGL context\n" );
            _glfwPlatformCloseWindow();
            return GL_FALSE;
        }

        if (_glfwLibrary.Unbundled)
        {
            if( GetCurrentProcess( &psn ) != noErr )
            {
                fprintf( stderr, "glfwOpenWindow failing because it can't get its PSN\n" );
                _glfwPlatformCloseWindow();
                return GL_FALSE;
            }

    	    if( TransformProcessType( &psn, kProcessTransformToForegroundApplication ) != noErr )
            {
                fprintf( stderr, "glfwOpenWindow failing because it can't become a foreground application\n" );
                _glfwPlatformCloseWindow();
                return GL_FALSE;
            }
            
            /* Keith Bauer 2007-07-12 - I don't believe this is desirable
    	    if( SetFrontProcess( &psn ) != noErr )
            {
                fprintf( stderr, "glfwOpenWindow failing because it can't become the front process\n" );
                _glfwPlatformCloseWindow();
                return GL_FALSE;
            }
            */
        }
	    
        // create window
        Rect windowContentBounds;
        windowContentBounds.left = 0;
        windowContentBounds.top = 0;
        windowContentBounds.right = width;
        windowContentBounds.bottom = height;

        windowAttributes = ( kWindowCloseBoxAttribute        \
                           | kWindowCollapseBoxAttribute     \
                           | kWindowStandardHandlerAttribute );

        if( hints->WindowNoResize )
        {
            windowAttributes |= kWindowLiveResizeAttribute;
        }
        else
        {
            windowAttributes |= ( kWindowFullZoomAttribute | kWindowResizableAttribute );
        }

        error = CreateNewWindow( kDocumentWindowClass,
                                 windowAttributes,
                                 &windowContentBounds,
                                 &( _glfwWin.MacWindow ) );
        if( ( error != noErr ) || ( _glfwWin.MacWindow == NULL ) )
        {
            fprintf( stderr, "glfwOpenWindow failing because it can't create a window\n" );
            _glfwPlatformCloseWindow();
            return GL_FALSE;
        }

        _glfwWin.WindowUPP = NewEventHandlerUPP( _glfwWindowEventHandler );

        error = InstallWindowEventHandler( _glfwWin.MacWindow,
                                           _glfwWin.WindowUPP,
                                           GetEventTypeCount( GLFW_WINDOW_EVENT_TYPES ),
                                           GLFW_WINDOW_EVENT_TYPES,
                                           NULL,
                                           NULL );
        if( error != noErr )
        {
            fprintf( stderr, "glfwOpenWindow failing because it can't install window event handlers\n" );
            _glfwPlatformCloseWindow();
            return GL_FALSE;
        }

        // Don't care if we fail here
        (void)SetWindowTitleWithCFString( _glfwWin.MacWindow, CFSTR( "GLFW Window" ) );
        (void)RepositionWindow( _glfwWin.MacWindow,
                                NULL,
                                kWindowCenterOnMainScreen );

        if( !aglSetDrawable( _glfwWin.AGLContext,
                             GetWindowPort( _glfwWin.MacWindow ) ) )
        {
            fprintf( stderr, "glfwOpenWindow failing because it can't draw to the window\n" );
            _glfwPlatformCloseWindow();
            return GL_FALSE;
        }

        // Make OpenGL context current
        if( !aglSetCurrentContext( _glfwWin.AGLContext ) )
        {
            fprintf( stderr, "glfwOpenWindow failing because it can't make the OpenGL context current\n" );
            _glfwPlatformCloseWindow();
            return GL_FALSE;
        }

        // show window
        ShowWindow( _glfwWin.MacWindow );

        return GL_TRUE;
    }
    else
    {
        CGDisplayErr cgErr;
        CGLError cglErr;

        CFDictionaryRef optimalMode;

        CGLPixelFormatObj CGLpfObj;
        long numCGLvs = 0;

        CGLPixelFormatAttribute CGLpixelFormatAttributes[64];
        int numCGLAttrs = 0;

        // variables for enumerating color depths
        GLint rgbColorDepth;
        GLint rgbaAccumDepth = 0;
        int rgbChannelDepth = 0;

        // CGL pixel format attributes
        _setCGLAttribute( kCGLPFADisplayMask,
                          CGDisplayIDToOpenGLDisplayMask( kCGDirectMainDisplay ) );

        if( hints->Stereo )
        {
            CGLpixelFormatAttributes[ numCGLAttrs++ ] = kCGLPFAStereo;
        }

	if( hints->Samples > 1 )
	{
	    _setCGLAttribute( kCGLPFASamples,       (CGLPixelFormatAttribute)hints->Samples );
	    _setCGLAttribute( kCGLPFASampleBuffers, (CGLPixelFormatAttribute)1 );
	    CGLpixelFormatAttributes[ numCGLAttrs++ ] = kCGLPFANoRecovery;
	}

        CGLpixelFormatAttributes[ numCGLAttrs++ ]     = kCGLPFAFullScreen;
        CGLpixelFormatAttributes[ numCGLAttrs++ ]     = kCGLPFADoubleBuffer;
        CGLpixelFormatAttributes[ numCGLAttrs++ ]     = kCGLPFAAccelerated;
        CGLpixelFormatAttributes[ numCGLAttrs++ ]     = kCGLPFANoRecovery;
        CGLpixelFormatAttributes[ numCGLAttrs++ ]     = kCGLPFAMinimumPolicy;

        _setCGLAttribute( kCGLPFAAccumSize,
                          (CGLPixelFormatAttribute)( hints->AccumRedBits \
                                                   + hints->AccumGreenBits \
                                                   + hints->AccumBlueBits \
                                                   + hints->AccumAlphaBits ) );

        _setCGLAttribute( kCGLPFAAlphaSize,   (CGLPixelFormatAttribute)alphabits );
        _setCGLAttribute( kCGLPFADepthSize,   (CGLPixelFormatAttribute)depthbits );
        _setCGLAttribute( kCGLPFAStencilSize, (CGLPixelFormatAttribute)stencilbits );
        _setCGLAttribute( kCGLPFAAuxBuffers,  (CGLPixelFormatAttribute)hints->AuxBuffers );

        CGLpixelFormatAttributes[ numCGLAttrs++ ]     = (CGLPixelFormatAttribute)NULL;

        // create a suitable pixel format with above attributes..
        cglErr = CGLChoosePixelFormat( CGLpixelFormatAttributes,
                                       &CGLpfObj,
                                       &numCGLvs );
        if( cglErr != kCGLNoError )
	{
	    return GL_FALSE;
	}

        // ..and create a rendering context using that pixel format
        cglErr = CGLCreateContext( CGLpfObj, NULL, &_glfwWin.CGLContext );
        if( cglErr != kCGLNoError )
	{
	    return GL_FALSE;
	}

        // enumerate depth of RGB channels - unlike AGL, CGL works with
        // a single parameter reflecting the full depth of the frame buffer
        (void)CGLDescribePixelFormat( CGLpfObj, 0, kCGLPFAColorSize, &rgbColorDepth );
        if( rgbColorDepth == 24 || rgbColorDepth == 32 )
	{
	    rgbChannelDepth = 8;
	}
        if( rgbColorDepth == 16 )
	{
	    rgbChannelDepth = 5;
	}

        // get pixel depth of accumulator - I haven't got the slightest idea
        // how this number conforms to any other channel depth than 8 bits,
        // so this might end up giving completely knackered results...
        (void)CGLDescribePixelFormat( CGLpfObj, 0, kCGLPFAAccumSize, &rgbaAccumDepth );
        if( rgbaAccumDepth == 32 )
	{
	    rgbaAccumDepth = 8;
	}

        // store values of pixel format for _glfwPlatformGetWindowParam's use
        _getCGLAttribute( kCGLPFAAccelerated, _glfwWin.Accelerated );
        _getCGLAttribute( rgbChannelDepth,    _glfwWin.RedBits );
        _getCGLAttribute( rgbChannelDepth,    _glfwWin.GreenBits );
        _getCGLAttribute( rgbChannelDepth,    _glfwWin.BlueBits );
        _getCGLAttribute( kCGLPFAAlphaSize,   _glfwWin.AlphaBits );
        _getCGLAttribute( kCGLPFADepthSize,   _glfwWin.DepthBits );
        _getCGLAttribute( kCGLPFAStencilSize, _glfwWin.StencilBits );
        _getCGLAttribute( rgbaAccumDepth,     _glfwWin.AccumRedBits );
        _getCGLAttribute( rgbaAccumDepth,     _glfwWin.AccumGreenBits );
        _getCGLAttribute( rgbaAccumDepth,     _glfwWin.AccumBlueBits );
        _getCGLAttribute( rgbaAccumDepth,     _glfwWin.AccumAlphaBits );
        _getCGLAttribute( kCGLPFAAuxBuffers,  _glfwWin.AuxBuffers );
        _getCGLAttribute( kCGLPFAStereo,      _glfwWin.Stereo );
        _glfwWin.RefreshRate = hints->RefreshRate;

        // destroy our pixel format
        (void)CGLDestroyPixelFormat( CGLpfObj );

        // capture the display for our application
        cgErr = CGCaptureAllDisplays();
        if( cgErr != kCGErrorSuccess )
	{
	    return GL_FALSE;
	}

        // find closest matching NON-STRETCHED display mode..
        optimalMode = CGDisplayBestModeForParametersAndRefreshRateWithProperty( kCGDirectMainDisplay,
	                                                                            rgbColorDepth,
	                                                                            width,
	/* Check further to the right -> */                                         height,
	                                                                            hints->RefreshRate,
	                                                                            NULL,
	                                                                            NULL );
        if( optimalMode == NULL )
	{
	    return GL_FALSE;
	}

        // ..and switch to that mode
        cgErr = CGDisplaySwitchToMode( kCGDirectMainDisplay, optimalMode );
        if( cgErr != kCGErrorSuccess )
	{
	    return GL_FALSE;
	}

        // switch to our OpenGL context, and bring it up fullscreen
        cglErr = CGLSetCurrentContext( _glfwWin.CGLContext );
        if( cglErr != kCGLNoError )
	{
	    return GL_FALSE;
	}

        cglErr = CGLSetFullScreen( _glfwWin.CGLContext );
        if( cglErr != kCGLNoError )
	{
	    return GL_FALSE;
	}

        return GL_TRUE;
    }
}
Exemplo n.º 25
0
/* krat: adding OpenGL support */
int Mac_GL_Init(_THIS)
{
#ifdef HAVE_OPENGL
	AGLPixelFormat format;
   	int i = 0;
	GLint attributes [ 24 ]; /* 24 is max possible in this setup */
	GLboolean noerr;
   
	attributes[i++] = AGL_RGBA;
	if ( this->gl_config.red_size   != 0 &&
	     this->gl_config.blue_size  != 0 &&
	     this->gl_config.green_size != 0 ) {
		attributes[i++] = AGL_RED_SIZE;
		attributes[i++] = this->gl_config.red_size;
		attributes[i++] = AGL_GREEN_SIZE;
		attributes[i++] = this->gl_config.green_size;
		attributes[i++] = AGL_BLUE_SIZE;
		attributes[i++] = this->gl_config.blue_size;
		attributes[i++] = AGL_ALPHA_SIZE;
		attributes[i++] = this->gl_config.alpha_size;
	}
	if ( this->gl_config.double_buffer ) {
		attributes[i++] = AGL_DOUBLEBUFFER;
	}
	if ( this->gl_config.depth_size != 0 ) {
		attributes[i++] = AGL_DEPTH_SIZE;
		attributes[i++] = this->gl_config.depth_size;
	}	
	if ( this->gl_config.stencil_size != 0 ) {
		attributes[i++] = AGL_STENCIL_SIZE;
		attributes[i++] = this->gl_config.stencil_size;
	}
	if ( this->gl_config.accum_red_size   != 0 &&
	     this->gl_config.accum_blue_size  != 0 &&
	     this->gl_config.accum_green_size != 0 ) {
		
		attributes[i++] = AGL_ACCUM_RED_SIZE;
		attributes[i++] = this->gl_config.accum_red_size;
		attributes[i++] = AGL_ACCUM_GREEN_SIZE;
		attributes[i++] = this->gl_config.accum_green_size;
		attributes[i++] = AGL_ACCUM_BLUE_SIZE;
		attributes[i++] = this->gl_config.accum_blue_size;
		attributes[i++] = AGL_ACCUM_ALPHA_SIZE;
		attributes[i++] = this->gl_config.accum_alpha_size;
	}
	if ( this->gl_config.stereo ) {
		attributes[i++] = AGL_STEREO;
	}
#if defined(AGL_SAMPLE_BUFFERS_ARB) && defined(AGL_SAMPLES_ARB)
	if ( this->gl_config.multisamplebuffers != 0 ) {
		attributes[i++] = AGL_SAMPLE_BUFFERS_ARB;
		attributes[i++] = this->gl_config.multisamplebuffers;
	}	
	if ( this->gl_config.multisamplesamples != 0 ) {
		attributes[i++] = AGL_SAMPLES_ARB;
		attributes[i++] = this->gl_config.multisamplesamples;
	}	
#endif
	attributes[i++] = AGL_ALL_RENDERERS;
	attributes[i]	= AGL_NONE;

	format = aglChoosePixelFormat(NULL, 0, attributes);
	if ( format == NULL ) {
		SDL_SetError("Couldn't match OpenGL desired format");
		return(-1);
	}

	glContext = aglCreateContext(format, NULL);
	if ( glContext == NULL ) {
		SDL_SetError("Couldn't create OpenGL context");
		return(-1);
	}
	aglDestroyPixelFormat(format);

    #if  TARGET_API_MAC_CARBON
    noerr = aglSetDrawable(glContext, GetWindowPort(SDL_Window));
    #else
	noerr = aglSetDrawable(glContext, (AGLDrawable)SDL_Window);
    #endif
    
	if(!noerr) {
		SDL_SetError("Unable to bind GL context to window");
		return(-1);
	}
	return(0);
#else
	SDL_SetError("OpenGL support not configured");
	return(-1);
#endif
}
void CL_DisplayWindow_OpenGL::create_window(const CL_DisplayWindowDescription &desc)
{
	OSStatus result;

	const CL_OpenGLWindowDescription_Generic *gl_desc = 0;
	gl_desc = dynamic_cast<const CL_OpenGLWindowDescription_Generic*>(desc.impl.get());

	fullscreen_width = desc.get_size().width;
	fullscreen_height = desc.get_size().height;

	disp_ref_count++;

	GLint gl_attribs_single[] =
	{
		AGL_RGBA,
		AGL_RED_SIZE, 4,
		AGL_GREEN_SIZE, 4,
		AGL_BLUE_SIZE, 4,
		AGL_DEPTH_SIZE, 16,
		AGL_NONE
	};

	GLint gl_attribs[32];
	int i = 0;
	
	if( gl_desc )
	{
		if( gl_desc->rgba ) gl_attribs[i++] = AGL_RGBA;
		if( gl_desc->doublebuffer ) gl_attribs[i++] = AGL_DOUBLEBUFFER;
		//if( gl_desc->stereo ) gl_attribs[i++] = AGL_STEREO;
		gl_attribs[i++] = AGL_BUFFER_SIZE;
		gl_attribs[i++] = gl_desc->buffer_size;
		gl_attribs[i++] = AGL_LEVEL;
		gl_attribs[i++] = gl_desc->level;
		gl_attribs[i++] = AGL_AUX_BUFFERS;
		gl_attribs[i++] = gl_desc->aux_buffers;
		gl_attribs[i++] = AGL_RED_SIZE; 
		gl_attribs[i++] = gl_desc->red_size;
		gl_attribs[i++] = AGL_GREEN_SIZE;
		gl_attribs[i++] = gl_desc->green_size;
		gl_attribs[i++] = AGL_BLUE_SIZE;
		gl_attribs[i++] = gl_desc->blue_size;
		gl_attribs[i++] = AGL_DEPTH_SIZE;
		gl_attribs[i++] = gl_desc->depth_size;
		gl_attribs[i++] = AGL_STENCIL_SIZE;
		gl_attribs[i++] = gl_desc->stencil_size;
		gl_attribs[i++] = AGL_ACCUM_RED_SIZE;
		gl_attribs[i++] = gl_desc->accum_red_size;
		gl_attribs[i++] = AGL_ACCUM_GREEN_SIZE;
		gl_attribs[i++] = gl_desc->accum_green_size;
		gl_attribs[i++] = AGL_ACCUM_BLUE_SIZE;
		gl_attribs[i++] = gl_desc->accum_blue_size;
		gl_attribs[i++] = AGL_ACCUM_ALPHA_SIZE;
		gl_attribs[i++] = gl_desc->accum_alpha_size;
		gl_attribs[i++] = AGL_ACCUM_RED_SIZE;
		gl_attribs[i++] = gl_desc->accum_red_size;
//		gl_attribs[i++] = AGL_FULLSCREEN;
	}
	else
	{
		gl_attribs[i++] = AGL_RGBA;
		gl_attribs[i++] = AGL_NO_RECOVERY;
		gl_attribs[i++] = AGL_DOUBLEBUFFER;
		gl_attribs[i++] = AGL_DEPTH_SIZE;
		gl_attribs[i++] = 16;
	} 
/*	
	else
	{
		gl_attribs[i++] = AGL_RGBA;
		gl_attribs[i++] = AGL_DOUBLEBUFFER;
		gl_attribs[i++] = AGL_RED_SIZE;
		gl_attribs[i++] = 4;
		gl_attribs[i++] = AGL_GREEN_SIZE;
		gl_attribs[i++] = 4;
		gl_attribs[i++] = AGL_BLUE_SIZE;
		gl_attribs[i++] = 4;
		gl_attribs[i++] = AGL_DEPTH_SIZE;
		gl_attribs[i++] = 16;
//		gl_attribs[i++] = AGL_FULLSCREEN;
	}
*/

	gl_attribs[i] = AGL_NONE;

	CGDirectDisplayID display = CGMainDisplayID();
	GDHandle gdhDisplay, *pgdhDisplay;
	int numDisplay;

	pgdhDisplay = &gdhDisplay;
	
	if (noErr == DMGetGDeviceByDisplayID ((DisplayIDType)display, pgdhDisplay, false)) 
		numDisplay = 1;	
	else 
	{
		pgdhDisplay = 0;
		numDisplay = 0;
	}
		
	AGLPixelFormat pixelformat;	
	pixelformat = aglChoosePixelFormat(pgdhDisplay, numDisplay, gl_attribs);
	win_context = aglCreateContext(pixelformat, share_context);
	if (!share_context) share_context = win_context;
	aglDestroyPixelFormat(pixelformat);
	gl_attribs[i++] = AGL_FULLSCREEN;
	gl_attribs[i] = AGL_NONE;
	pixelformat = aglChoosePixelFormat(pgdhDisplay, numDisplay, gl_attribs);
	fs_context = aglCreateContext(pixelformat, win_context);
	aglDestroyPixelFormat(pixelformat);

	if (!(win_context && fs_context)) 
	{
		printf("Requested visual not supported by your OpenGL implementation. Falling back on singlebuffered Visual!\n");
		pixelformat = aglChoosePixelFormat(0, 0, gl_attribs_single);
		win_context = aglCreateContext(pixelformat, share_context);
		aglDestroyPixelFormat(pixelformat);
		fs_context = 0;
	}

	WindowAttributes style = kWindowCloseBoxAttribute | kWindowStandardHandlerAttribute;
	if (desc.get_allow_resize()) style |= kWindowResizableAttribute | kWindowFullZoomAttribute;
	Rect window_rect;
	SetRect(&window_rect, 50, 50, 50+desc.get_size().width, 50+desc.get_size().height);
	result = CreateNewWindow(kDocumentWindowClass, style, &window_rect, &window_ref);
	if (result != noErr)
		printf("Could not create window, due to error %d\n", (int)result);

	// set title of window:
	set_title(desc.get_title());

	// Set standard arrow cursor:
	InitCursor(); // do we need to do this? -- iMBN, 13. may 2004
	
	// Create input devices for window:
	keyboard = CL_InputDevice(new CL_InputDevice_MacKeyboard(this));
	mouse	= CL_InputDevice(new CL_InputDevice_MacMouse(this));

	get_ic()->clear();
	get_ic()->add_keyboard(keyboard);
	get_ic()->add_mouse(mouse);

//	buffer_front = CL_PixelBuffer(new CL_PixelBuffer_OpenGL_Frame(CL_FRONT, gc));
//	buffer_back = CL_PixelBuffer(new CL_PixelBuffer_OpenGL_Frame(CL_BACK, gc));

	if (!aglSetDrawable(win_context, GetWindowPort(window_ref)))
	{
		printf("Unable to set drawable");
	}
	
	if (desc.is_fullscreen())
		set_fullscreen(desc.get_size().width, desc.get_size().height, desc.get_bpp(), desc.get_refresh_rate());
	else {
		fullscreen = true;  // not really, but need to fool set_windowed
		set_windowed();
	}

	ShowWindow(window_ref);
}
Exemplo n.º 27
0
/*
** OS Specific windowing context creation - essential for creating the OpenGL drawing context
*/
AESDK_OpenGL_Err AESDK_OpenGL_Startup(AESDK_OpenGL_EffectCommonData& inData)
{
	AESDK_OpenGL_Err result = AESDK_OpenGL_OK;
	inData.mUsingShaderB = false; //default value
	try
	{
#ifdef AE_OS_WIN
		WNDCLASSEX winClass; 
		MSG        uMsg;

		::memset(&uMsg,0,sizeof(uMsg));

		winClass.lpszClassName = "AESDK_OpenGL_Win_Class";
		winClass.cbSize        = sizeof(WNDCLASSEX);
		winClass.style         = CS_HREDRAW | CS_VREDRAW;
		winClass.lpfnWndProc   = ::DefWindowProc;
		winClass.hInstance     = NULL;
		winClass.hIcon	       = NULL;
		winClass.hIconSm	   = NULL;
		winClass.hCursor       = ::LoadCursor(NULL, IDC_ARROW);
		winClass.hbrBackground = (HBRUSH)::GetStockObject(BLACK_BRUSH);
		winClass.lpszMenuName  = NULL;
		winClass.cbClsExtra    = 0;
		winClass.cbWndExtra    = 0;
		
		if( !(::RegisterClassEx(&winClass)) )
			GL_CHECK(AESDK_OpenGL_OS_Load_Err);

		inData.mHWnd = ::CreateWindowEx( NULL, "AESDK_OpenGL_Win_Class", 
								 "OpenGL-using FBOs in AE",
									0,0, 
									0, 50, 50,
									NULL, 
									NULL, 
									NULL,
									NULL	);

		if( inData.mHWnd == NULL )
			GL_CHECK(AESDK_OpenGL_OS_Load_Err);
		
		GLuint PixelFormat;
		PIXELFORMATDESCRIPTOR pfd;
		::ZeroMemory( &pfd, sizeof( pfd ) );

		pfd.nSize      = sizeof(PIXELFORMATDESCRIPTOR);
		pfd.nVersion   = 1;
		pfd.dwFlags    = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER ;
		pfd.iPixelType = PFD_TYPE_RGBA;
		pfd.cColorBits = 32;
		pfd.cDepthBits = 8;
		
		
		inData.mHDC = ::GetDC( inData.mHWnd );
		PixelFormat = ChoosePixelFormat( inData.mHDC, &pfd );
		SetPixelFormat( inData.mHDC, PixelFormat, &pfd);
		
		inData.mHRC = wglCreateContext( inData.mHDC );
		wglMakeCurrent( inData.mHDC, inData.mHRC );

		//check for the appropriate extensions -  EXT_framebuffer_object
		char *ext = (char*)glGetString( GL_EXTENSIONS );
		if( ::strstr( ext, "EXT_framebuffer_object" ) == NULL )
		{		
			GL_CHECK(AESDK_OpenGL_Extensions_Err);
		}
		else
		{
			glIsRenderbufferEXT = (PFNGLISRENDERBUFFEREXTPROC)GetProcAddress("glIsRenderbufferEXT");
			glBindRenderbufferEXT = (PFNGLBINDRENDERBUFFEREXTPROC)GetProcAddress("glBindRenderbufferEXT");
			glDeleteRenderbuffersEXT = (PFNGLDELETERENDERBUFFERSEXTPROC)GetProcAddress("glDeleteRenderbuffersEXT");
			glGenRenderbuffersEXT = (PFNGLGENRENDERBUFFERSEXTPROC)GetProcAddress("glGenRenderbuffersEXT");
			glRenderbufferStorageEXT = (PFNGLRENDERBUFFERSTORAGEEXTPROC)GetProcAddress("glRenderbufferStorageEXT");
			glGetRenderbufferParameterivEXT = (PFNGLGETRENDERBUFFERPARAMETERIVEXTPROC)GetProcAddress("glGetRenderbufferParameterivEXT");
			glIsFramebufferEXT = (PFNGLISFRAMEBUFFEREXTPROC)GetProcAddress("glIsFramebufferEXT");
			glBindFramebufferEXT = (PFNGLBINDFRAMEBUFFEREXTPROC)GetProcAddress("glBindFramebufferEXT");
			glDeleteFramebuffersEXT = (PFNGLDELETEFRAMEBUFFERSEXTPROC)GetProcAddress("glDeleteFramebuffersEXT");
			glGenFramebuffersEXT = (PFNGLGENFRAMEBUFFERSEXTPROC)GetProcAddress("glGenFramebuffersEXT");
			glCheckFramebufferStatusEXT = (PFNGLCHECKFRAMEBUFFERSTATUSEXTPROC)GetProcAddress("glCheckFramebufferStatusEXT");
			glFramebufferTexture1DEXT = (PFNGLFRAMEBUFFERTEXTURE1DEXTPROC)GetProcAddress("glFramebufferTexture1DEXT");
			glFramebufferTexture2DEXT = (PFNGLFRAMEBUFFERTEXTURE2DEXTPROC)GetProcAddress("glFramebufferTexture2DEXT");
			glFramebufferTexture3DEXT = (PFNGLFRAMEBUFFERTEXTURE3DEXTPROC)GetProcAddress("glFramebufferTexture3DEXT");
			glFramebufferRenderbufferEXT = (PFNGLFRAMEBUFFERRENDERBUFFEREXTPROC)GetProcAddress("glFramebufferRenderbufferEXT");
			glGetFramebufferAttachmentParameterivEXT = (PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVEXTPROC)GetProcAddress("glGetFramebufferAttachmentParameterivEXT");
			glGenerateMipmapEXT = (PFNGLGENERATEMIPMAPEXTPROC)GetProcAddress("glGenerateMipmapEXT");
			glActiveTexture = (PFNGLACTIVETEXTUREPROC)GetProcAddress("glActiveTexture");

			if( !glIsRenderbufferEXT || !glBindRenderbufferEXT || !glDeleteRenderbuffersEXT || 
				!glGenRenderbuffersEXT || !glRenderbufferStorageEXT || !glGetRenderbufferParameterivEXT || 
				!glIsFramebufferEXT || !glBindFramebufferEXT || !glDeleteFramebuffersEXT || 
				!glGenFramebuffersEXT || !glCheckFramebufferStatusEXT || !glFramebufferTexture1DEXT || 
				!glFramebufferTexture2DEXT || !glFramebufferTexture3DEXT || !glFramebufferRenderbufferEXT||  
				!glGetFramebufferAttachmentParameterivEXT || !glGenerateMipmapEXT || !glActiveTexture)
			{
				GL_CHECK(AESDK_OpenGL_Extensions_Err);
			}
			
		}
		
		char *extP = (char*)glGetString( GL_EXTENSIONS );
		if( ::strstr( extP, "GL_ARB_shading_language_100" ) == NULL )
		{
			//This extension string indicates that the OpenGL Shading Language,
			// version 1.00, is supported.
			GL_CHECK(AESDK_OpenGL_ShaderInit_Err);
		}
	
		//check for the appropriate extensions -  EXT_framebuffer_object
		if( ::strstr( extP, "GL_ARB_shader_objects" ) == NULL )
		{		
			GL_CHECK(AESDK_OpenGL_Extensions_Err);
		}
		else
		{
			glCreateProgramObjectARB  = (PFNGLCREATEPROGRAMOBJECTARBPROC)GetProcAddress("glCreateProgramObjectARB");
			glDeleteObjectARB         = (PFNGLDELETEOBJECTARBPROC)GetProcAddress("glDeleteObjectARB");
			glUseProgramObjectARB     = (PFNGLUSEPROGRAMOBJECTARBPROC)GetProcAddress("glUseProgramObjectARB");
			glCreateShaderObjectARB   = (PFNGLCREATESHADEROBJECTARBPROC)GetProcAddress("glCreateShaderObjectARB");
			glShaderSourceARB         = (PFNGLSHADERSOURCEARBPROC)GetProcAddress("glShaderSourceARB");
			glCompileShaderARB        = (PFNGLCOMPILESHADERARBPROC)GetProcAddress("glCompileShaderARB");
			glGetObjectParameterivARB = (PFNGLGETOBJECTPARAMETERIVARBPROC)GetProcAddress("glGetObjectParameterivARB");
			glAttachObjectARB         = (PFNGLATTACHOBJECTARBPROC)GetProcAddress("glAttachObjectARB");
			glGetInfoLogARB           = (PFNGLGETINFOLOGARBPROC)GetProcAddress("glGetInfoLogARB");
			glLinkProgramARB          = (PFNGLLINKPROGRAMARBPROC)GetProcAddress("glLinkProgramARB");
			glGetUniformLocationARB   = (PFNGLGETUNIFORMLOCATIONARBPROC)GetProcAddress("glGetUniformLocationARB");
			glUniform4fARB            = (PFNGLUNIFORM4FARBPROC)GetProcAddress("glUniform4fARB");
			glUniform1iARB            = (PFNGLUNIFORM1IARBPROC)GetProcAddress("glUniform1iARB");

			if( !glCreateProgramObjectARB || !glDeleteObjectARB || !glUseProgramObjectARB ||
				!glCreateShaderObjectARB || !glCreateShaderObjectARB || !glCompileShaderARB || 
				!glGetObjectParameterivARB || !glAttachObjectARB || !glGetInfoLogARB || 
				!glLinkProgramARB || !glGetUniformLocationARB || !glUniform4fARB ||
				!glUniform1iARB )
			{
				GL_CHECK(AESDK_OpenGL_Extensions_Err);
			}
		}
		
#elif defined(AE_OS_MAC)
		Rect rect;
		SetRect(&rect, 0, 0, 50, 50);
		if ( noErr != CreateNewWindow(kDocumentWindowClass, kWindowStandardDocumentAttributes, &rect, &inData.mMacWnd))
			GL_CHECK(AESDK_OpenGL_OS_Load_Err);
		
		GLint aAttribs[64];
		u_short nIndexS= -1;

		// NO color index support
		aAttribs[++nIndexS]= AGL_RGBA;
		// double buffering
		aAttribs[++nIndexS]=AGL_DOUBLEBUFFER;
	    
		// color
		aAttribs[++nIndexS] = AGL_RED_SIZE;
		aAttribs[++nIndexS] = 8;
		aAttribs[++nIndexS] = AGL_GREEN_SIZE;
		aAttribs[++nIndexS] = 8;
		aAttribs[++nIndexS] = AGL_BLUE_SIZE;
		aAttribs[++nIndexS] = 8;
		aAttribs[++nIndexS] = AGL_ALPHA_SIZE;
		aAttribs[++nIndexS] = 8;
	    
		aAttribs[++nIndexS] = AGL_NONE;

		// get an appropriate pixel format
		AGLPixelFormat oPixelFormat = aglChoosePixelFormat(	NULL,
															0,
															aAttribs);
		if( oPixelFormat == NULL )
			GL_CHECK(AESDK_OpenGL_OS_Load_Err);
	    
		// create the context from the pixel format
		inData.mAGLContext = aglCreateContext(oPixelFormat,NULL);
	    
		if( NULL == inData.mAGLContext )
			GL_CHECK(AESDK_OpenGL_Extensions_Err);
	    
		// otherwise clean-up the pixel format
		aglDestroyPixelFormat(oPixelFormat);

		//attach the window
		if ( !aglSetDrawable (inData.mAGLContext, GetWindowPort(inData.mMacWnd)) )
			GL_CHECK(AESDK_OpenGL_Extensions_Err);

		glFlush();
		aglSetCurrentContext(inData.mAGLContext);
#endif
	}
	catch(AESDK_OpenGL_Err& err)
	{
		result = err;
	}

	return result;
}
Exemplo n.º 28
0
    void OSXCarbonWindow::setFullscreen(bool fullScreen, unsigned int width, unsigned int height)
    {
        if (mIsFullScreen != fullScreen || width != mWidth || height != mHeight)
        {
            // Set the full screen flag
            mIsFullScreen = fullScreen;

            createAGLContext(mFSAA, mColourDepth);

            if (mIsFullScreen)
            {
                GLRenderSystem *rs = static_cast<GLRenderSystem*>(Root::getSingleton().getRenderSystem());

                CGLContextObj share = NULL;
                aglGetCGLContext(mAGLContext, (void**)&share);

                // Create the CGL context object if it doesn't already exist, sharing the AGL context.
                if(!mCGLContext)
                {
                    void *cglPixFormat;
                    aglGetCGLPixelFormat(mAGLPixelFormat, (void **)&cglPixFormat);
                    mCGLContext = OGRE_NEW OSXCGLContext(mCGLContextObj, (CGLPixelFormatObj) cglPixFormat);
                }

                // Create the context, keeping the current colour depth and FSAA settings
                createCGLFullscreen(width, height, getColourDepth(), getFSAA(), share);
                rs->_switchContext(mContext);

                // Hide the Carbon window
                HideWindow(mWindow);

                // And tell the rendersystem to stop rendering to it too
                WindowEventUtilities::_removeRenderWindow(this);
            }
            else
            {
                // Create a new AGL context and pixel format if necessary
                createAGLContext(mFSAA, mColourDepth);

                // Create a window if we haven't already, existence check is done within the functions
                if(!mWindow)
                {
                    if(mIsExternal)
                        createWindowFromExternal(mView);
                    else
                        createNewWindow(width, height, mWindowTitle);
                }

                // Destroy the current CGL context, we will create a new one when/if we go back to full screen
                destroyCGLFullscreen();

                // Set the drawable, and current context
                // If you do this last, there is a moment before the rendering window pops-up
                #if defined(MAC_OS_X_VERSION_10_4) && MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_4
                    aglSetDrawable(mAGLContext, GetWindowPort(mWindow));
                #else
                    aglSetWindowRef(mAGLContext, mWindow);
                #endif
                aglSetCurrentContext(mAGLContext);

                if(!mCarbonContext)
                {
                    mCarbonContext = OGRE_NEW OSXCarbonContext(mAGLContext, mAGLPixelFormat);
                }
                
                GLRenderSystem *rs = static_cast<GLRenderSystem*>(Root::getSingleton().getRenderSystem());
                mContext = mCarbonContext;
                rs->_switchContext(mContext);

                WindowEventUtilities::_addRenderWindow(this);

                ShowWindow(mWindow);
                SelectWindow(mWindow);
                RepositionWindow(mWindow, NULL, kWindowCenterOnMainScreen);
            }
            mWidth = width;
            mHeight = height;
        }
    }
Exemplo n.º 29
0
    //-------------------------------------------------------------------------------------------------//
    void OSXCarbonWindow::create( const String& name, unsigned int width, unsigned int height,
                    bool fullScreen, const NameValuePairList *miscParams )
    {
        bool hasDepthBuffer = false;
        String title = name;
        size_t fsaa_samples = 0;
        int left = 0;
        int top = 0;
        bool vsync = false;
        bool hidden = false;
        int depth = 32;

        if( miscParams )
        {
            NameValuePairList::const_iterator opt(NULL);
            NameValuePairList::const_iterator end = miscParams->end();

            // Full screen anti aliasing
            if((opt = miscParams->find("FSAA")) != end) 
                fsaa_samples = StringConverter::parseUnsignedInt( opt->second );

            if((opt = miscParams->find("left")) != end) 
                left = StringConverter::parseUnsignedInt( opt->second );

            if((opt = miscParams->find("top")) != end) 
                top = StringConverter::parseUnsignedInt( opt->second );

            if((opt = miscParams->find("title")) != end) 
                title = opt->second;

            if((opt = miscParams->find("vsync")) != end) 
                vsync = StringConverter::parseBool(opt->second);

            if((opt = miscParams->find("hidden")) != end) 
                hidden = StringConverter::parseBool(opt->second);

            if((opt = miscParams->find("gamma")) != end) 
				mHwGamma = StringConverter::parseBool(opt->second);

            if((opt = miscParams->find("depthBuffer")) != end) 
                hasDepthBuffer = StringConverter::parseBool( opt->second );
            
            if((opt = miscParams->find("colourDepth")) != end) 
                depth = StringConverter::parseUnsignedInt( opt->second );

            if((opt = miscParams->find("Full Screen")) != end) 
                fullScreen = StringConverter::parseBool( opt->second );
        }

        if(fullScreen)
        {
            setFullscreen(fullScreen, width, height);
        }
        else
        {
            createAGLContext(fsaa_samples, depth);

            NameValuePairList::const_iterator opt(NULL);
            if(miscParams)
                opt = miscParams->find("externalWindowHandle");

            if(!miscParams || opt == miscParams->end())
                createNewWindow(width, height, title.c_str());
            else
                createWindowFromExternal((HIViewRef)StringConverter::parseUnsignedLong(opt->second));

            // Set the drawable, and current context
            // If you do this last, there is a moment before the rendering window pops-up
            // This could go once inside each case above, before the window is displayed,
            // if desired.
    #if defined(MAC_OS_X_VERSION_10_4) && MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_4
            aglSetDrawable(mAGLContext, GetWindowPort(mWindow));
    #else
            aglSetWindowRef(mAGLContext, mWindow);
    #endif
            aglSetCurrentContext(mAGLContext);

            // Give a copy of our context to the render system
            if(!mCarbonContext)
            {
                mCarbonContext = OGRE_NEW OSXCarbonContext(mAGLContext, mAGLPixelFormat);
                mContext = mCarbonContext;
            }
        }

        // Apply vsync settings. call setVSyncInterval first to avoid 
		// setting vsync more than once.
        setVSyncEnabled(vsync);
        setHidden(hidden);

        mName = name;
        mWidth = width;
        mHeight = height;
        mColourDepth = depth;
        mFSAA = fsaa_samples;
        mIsFullScreen = fullScreen;
        mActive = true;
        mClosed = false;
        mCreated = true;
    }
Exemplo n.º 30
0
bool nglContext::Build(WindowRef Win, const nglContextInfo& rInfo, const nglContext* pShared, bool Fullscreen)
{
  mTargetAPI = rInfo.TargetAPI;
  
#ifndef __NOGLCONTEXT__
  mFullscreen = Fullscreen;

  std::vector<GLint> attribs;
  attribs.push_back(AGL_RGBA);
  if (rInfo.FrameCnt != 1)
    attribs.push_back(AGL_DOUBLEBUFFER);
  
  attribs.push_back(AGL_DEPTH_SIZE);
  attribs.push_back(rInfo.DepthBits);
  
  attribs.push_back(AGL_STENCIL_SIZE);
  attribs.push_back(rInfo.StencilBits);

  if (rInfo.AuxCnt)
  {
    attribs.push_back(AGL_AUX_BUFFERS);
    attribs.push_back(rInfo.AuxCnt);
  }
  
  if (rInfo.AABufferCnt)
  {
    attribs.push_back(AGL_SAMPLE_BUFFERS_ARB);
    attribs.push_back(rInfo.AABufferCnt);
    attribs.push_back(AGL_SAMPLES_ARB);
    attribs.push_back(rInfo.AASampleCnt);
  }

  attribs.push_back(AGL_RED_SIZE);
  attribs.push_back(rInfo.FrameBitsR);
  attribs.push_back(AGL_GREEN_SIZE);
  attribs.push_back(rInfo.FrameBitsG);
  attribs.push_back(AGL_BLUE_SIZE);
  attribs.push_back(rInfo.FrameBitsB);
  attribs.push_back(AGL_ALPHA_SIZE);
  attribs.push_back(rInfo.FrameBitsA);
  attribs.push_back(AGL_PIXEL_SIZE);
  attribs.push_back(rInfo.FrameBitsR + rInfo.FrameBitsG + rInfo.FrameBitsB + rInfo.FrameBitsA);

  if (rInfo.AccumBitsR || rInfo.AccumBitsG || rInfo.AccumBitsB || rInfo.AccumBitsA)
  {
    attribs.push_back(AGL_ACCUM_RED_SIZE);
    attribs.push_back(rInfo.AccumBitsR);
    attribs.push_back(AGL_ACCUM_GREEN_SIZE);
    attribs.push_back(rInfo.AccumBitsG);
    attribs.push_back(AGL_ACCUM_BLUE_SIZE);
    attribs.push_back(rInfo.AccumBitsB);
    attribs.push_back(AGL_ACCUM_ALPHA_SIZE);
    attribs.push_back(rInfo.AccumBitsA);
  }

  
  if (rInfo.Stereo) 
    attribs.push_back(AGL_STEREO);
  
  attribs.push_back(AGL_MINIMUM_POLICY);
  attribs.push_back(AGL_NO_RECOVERY);
  
  if (rInfo.CopyOnSwap)
    attribs.push_back(AGL_BACKING_STORE);
  
  attribs.push_back(AGL_NONE);
     
  /* Choose pixel format */
  AGLPixelFormat Format = aglChoosePixelFormat(NULL, 0, &attribs[0]);
  
  //NGL_OUT("Pixel Format: 0x%x\n", Format);
  
  if (!Format)
  {
    if (rInfo.CopyOnSwap)
    {
      attribs[attribs.size() - 2] = AGL_NONE;
      Format = aglChoosePixelFormat(NULL, 0, &attribs[0]);
    } 

    if (!Format)
    {
      SetError(_T("context"), NGL_CONTEXT_ENOMATCH);
      return false;
    }
  }

  //DumpFormat(Format);
  
  /* Create an AGL context */
  mCtx = aglCreateContext(Format, pShared?pShared->mCtx:NULL);
  long err = aglGetError();

  GLint value;
  aglDescribePixelFormat(Format, AGL_DOUBLEBUFFER, &value);
  mContextInfo.FrameCnt = value ? 2 : 1;     ///< Number of frame buffers (two means double-buffering)

  aglDescribePixelFormat(Format, AGL_RED_SIZE, (GLint*)&mContextInfo.FrameBitsR);   ///< Bits per red component (frame buffer)
  aglDescribePixelFormat(Format, AGL_GREEN_SIZE, (GLint*)&mContextInfo.FrameBitsG);   ///< Bits per green component (frame buffer)
  aglDescribePixelFormat(Format, AGL_BLUE_SIZE, (GLint*)&mContextInfo.FrameBitsB);   ///< Bits per blue component (frame buffer)
  aglDescribePixelFormat(Format, AGL_ALPHA_SIZE, (GLint*)&mContextInfo.FrameBitsA);   ///< Bits per alpha component (frame buffer)
  aglDescribePixelFormat(Format, AGL_DEPTH_SIZE, (GLint*)&mContextInfo.DepthBits);    ///< Depth buffer resolution (ie. Z buffer, 0 means no Z buffer)
  aglDescribePixelFormat(Format, AGL_STENCIL_SIZE, (GLint*)&mContextInfo.StencilBits);  ///< Stencil buffer resolution (0 means no stencil)
  aglDescribePixelFormat(Format, AGL_ACCUM_RED_SIZE, (GLint*)&mContextInfo.AccumBitsR);   ///< Bits per red component (accumulator buffer)
  aglDescribePixelFormat(Format, AGL_ACCUM_GREEN_SIZE, (GLint*)&mContextInfo.AccumBitsG);   ///< Bits per green component (accumulator buffer)
  aglDescribePixelFormat(Format, AGL_ACCUM_BLUE_SIZE, (GLint*)&mContextInfo.AccumBitsB);   ///< Bits per blue component (accumulator buffer)
  aglDescribePixelFormat(Format, AGL_ACCUM_ALPHA_SIZE, (GLint*)&mContextInfo.AccumBitsA);   ///< Bits per alpha component (accumulator buffer)
  aglDescribePixelFormat(Format, AGL_AUX_BUFFERS, (GLint*)&mContextInfo.AuxCnt);       ///< Number of auxiliary buffers
  aglDescribePixelFormat(Format, AGL_SAMPLE_BUFFERS_ARB, (GLint*)&mContextInfo.AABufferCnt);  ///< Number of anti-aliasing buffers
  aglDescribePixelFormat(Format, AGL_SAMPLES_ARB, (GLint*)&mContextInfo.AASampleCnt);  ///< Anti-alisaing oversampling count
  aglDescribePixelFormat(Format, AGL_STEREO, &value);       ///< Stereoscopic display

  mContextInfo.Stereo = value != 0;
  mContextInfo.Offscreen = false;       ///< This context can render in memory instead of to a window. (false by default).
  mContextInfo.RenderToTexture = false; ///< This context must be able to be bound as a texture. (false by default)
  aglDescribePixelFormat(Format, AGL_BACKING_STORE, &value);  ///< This context must be able to use copy the back buffer to the front buffer instead of swaping them. (false by default) 
  mContextInfo.CopyOnSwap = value != 0;
  if (rInfo.CopyOnSwap && !mContextInfo.CopyOnSwap)
    mValidBackBufferRequestedNotGranted = true;
  
  aglDestroyPixelFormat(Format);
  if (!mCtx)
  {
    SetError(_T("context"), NGL_CONTEXT_EGLCTX);
    /*
    switch (err)
    {
    case AGL_BAD_MATCH:
      NGL_OUT("AGL Error: Bad Context Match (shared context incompatible with requested pixel format).\n");
      break;
    case AGL_BAD_CONTEXT:
      NGL_OUT("AGL Error: Bad Shared Context.\n");
      break;
    case AGL_BAD_PIXELFMT:
      NGL_OUT("AGL Error: Bad Pixel Format.\n");
      break;
    default:
      NGL_OUT("AGL Error: Unknown error\n");
      break;
    }
    */
    return false;
  }

  /* Attach the context to the window */
  if (!aglSetDrawable(mCtx, GetWindowPort (Win)))
  {
    SetError(_T("context"), NGL_CONTEXT_EBIND);
    return false;
  }

  {
    CGLError err = kCGLNoError;
    CGLContextObj ctx = CGLGetCurrentContext();
    
    // Enable the multi-threading
    //err =  CGLEnable( ctx, kCGLCEMPEngine);
    
    if (err != kCGLNoError )
    {
      // Multi-threaded execution is possibly not available
      // Insert your code to take appropriate action
    }
  }
  
  GLint vsync = rInfo.VerticalSync ? 1 : 0;
  aglSetInteger(mCtx, AGL_SWAP_INTERVAL, &vsync);
  
  InitPainter();
  MakeCurrent(Win);
#endif
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  return true;
}