bool OPENGL_PBUFFER::
Create(int width, int height)
{
    if (pbuffer) {
        LOG::cerr << "Destroying old pbuffer before creating new one" << std::endl;
        Destroy();
    }

    GLint attributes[] = {AGL_RGBA,AGL_DOUBLEBUFFER,AGL_NONE};
    AGLPixelFormat format = aglChoosePixelFormat(NULL, 0, attributes);
    if(format==NULL){
        LOG::cout<<"Could not set up the pixel format"<<std::endl;return false;}
    
    AGLContext context = aglCreateContext(format, NULL);
    if(context==NULL){
        LOG::cout<<"Could not set up the pbuffer context"<<std::endl;return false;}
    aglSetCurrentContext(context);

    if(!aglCreatePBuffer(width, height, GL_TEXTURE_2D, GL_RGBA, 0, &pbuffer)){
        LOG::cout<<"Error: couldn't create pbuffer"<<std::endl;
        LOG::cout<<aglErrorString(aglGetError());
        return false;
    }

    if(!aglSetPBuffer(context, pbuffer, 0, 0, aglGetVirtualScreen(context))){
        LOG::cout<<"Error: couldn't set pbuffer"<<std::endl;
        LOG::cout<<aglErrorString(aglGetError());
        return false;
    }
       
    return true;  /* Success!! */
}
Exemple #2
0
static void wxLogAGLError(const char *func)
{
    const int err = aglGetError();

    wxLogError(_("OpenGL function \"%s\" failed: %s (error %d)"),
               func, aglErrorString(err), err);
}
bool SkOSWindow::attachGL()
{
    if (NULL == fAGLCtx) {
        fAGLCtx = create_gl((WindowRef)fHWND);
        if (NULL == fAGLCtx) {
            return false;
        }
    }

    GLboolean success = true;

    int width, height;

    success = aglSetWindowRef((AGLContext)fAGLCtx, (WindowRef)fHWND);
    width = this->width();
    height = this->height();

    GLenum err = aglGetError();
    if (err) {
        SkDebugf("---- aglSetWindowRef %d %d %s [%d %d]\n", success, err,
                 aglErrorString(err), width, height);
    }

    if (success) {
        glViewport(0, 0, width, height);
        glClearColor(0, 0, 0, 0);
        glClearStencil(0);
        glClear(GL_COLOR_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
    }
    return success;
}
Exemple #4
0
int _SYS_AGLTRACE(int err, int line)
{
	int ret = aglGetError();
	if (ret)
	printf("%s(%d) : %s (%d)\n", __FILE__, line, aglErrorString(ret), err);
    return err;
}
Exemple #5
0
static void setup_offscreen_gl(const SkBitmap& offscreen, WindowRef wref) {
    GLboolean success = true;

#ifdef USE_OFFSCREEN
    success = aglSetOffScreen(gAGLContext,
                              offscreen.width(),
                              offscreen.height(),
                              offscreen.rowBytes(),
                              offscreen.getPixels());
#else
    success = aglSetWindowRef(gAGLContext, wref);
#endif

    GLenum err = aglGetError();
    if (err) {
        SkDebugf("---- setoffscreen %d %d %s [%d %d]\n", success, err,
                 aglErrorString(err), offscreen.width(), offscreen.height());
    }

    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    glHint(GL_LINE_SMOOTH_HINT, GL_DONT_CARE);
    glEnable(GL_TEXTURE_2D);

    glClearColor(0, 0, 0, 0);
    glClear(GL_COLOR_BUFFER_BIT);
}
//проверка ошибок Agl Framework
void check_agl_error (const char* source)
{
  GLenum err = aglGetError();

  if (AGL_NO_ERROR == err)
    return;

  throw xtl::format_operation_exception (source, "Agl error. %s", aglErrorString (err));
}
Exemple #7
0
GLboolean glewCreateContext ()
{
  int attrib[] = { AGL_RGBA, AGL_NONE };
  AGLPixelFormat pf;
  /*int major, minor;
  SetPortWindowPort(wnd);
  aglGetVersion(&major, &minor);
  fprintf(stderr, "GL %d.%d\n", major, minor);*/
  pf = aglChoosePixelFormat(NULL, 0, attrib);
  if (NULL == pf) return GL_TRUE;
  ctx = aglCreateContext(pf, NULL);
  if (NULL == ctx || AGL_NO_ERROR != aglGetError()) return GL_TRUE;
  aglDestroyPixelFormat(pf);
  /*aglSetDrawable(ctx, GetWindowPort(wnd));*/
  octx = aglGetCurrentContext();
  if (NULL == aglSetCurrentContext(ctx)) return GL_TRUE;
  return GL_FALSE;
}
Exemple #8
0
void *QGLContext::chooseMacVisual(GDHandle /* handle */)
{
    Q_D(QGLContext);
    AGLPixelFormat fmt;

    fmt = d->tryFormat(d->glFormat);
    if (!fmt && d->glFormat.stereo()) {
        d->glFormat.setStereo(false);
        fmt = d->tryFormat(d->glFormat);
    }
    if (!fmt && d->glFormat.sampleBuffers()) {
        d->glFormat.setSampleBuffers(false);
        fmt = d->tryFormat(d->glFormat);
    }
    if(!fmt)
        qWarning("QGLContext::chooseMacVisual: Unable to choose a pixel format (error: %d)",
                 (int)aglGetError());
    return fmt;
}
Exemple #9
0
int printRendererInfo(void)
{
	GLenum   err;
	GDHandle device;
	GLuint   dnum = 0;
	
	device = GetDeviceList();
	while(device)
	{
		DPRINTF(3,(fp,"\nDevice : %d\n", dnum));
		CheckGetRendererInfo(device);
		device = GetNextDevice(device);
		dnum++;
	}
		
	err = aglGetError();
	if(err != AGL_NO_ERROR) DPRINTF(3,(fp,"aglGetError - %s\n", aglErrorString(err)));

   return 1;
}
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;
}
Exemple #11
0
TextWriter::TextWriter(int in_x, int in_y, Renderer &in_renderer, bool in_centered, int in_size, std::wstring fontname) :
x(in_x), y(in_y), size(in_size), original_x(0), last_line_height(0), centered(in_centered), renderer(in_renderer)
{
   x += renderer.m_xoffset;
   original_x = x;

   y += renderer.m_yoffset;

#ifdef WIN32

   Context c = renderer.m_context;
   point_size = MulDiv(size, GetDeviceCaps(c, LOGPIXELSY), 72);

   HFONT font = 0;
   if (font_size_lookup[in_size] == 0)
   {
      // Set up the LOGFONT structure
      LOGFONT logical_font;
      logical_font.lfHeight = get_point_size();
      logical_font.lfWidth = 0;
      logical_font.lfEscapement = 0;
      logical_font.lfOrientation = 0;
      logical_font.lfWeight = FW_NORMAL;
      logical_font.lfItalic = false;
      logical_font.lfUnderline = false;
      logical_font.lfStrikeOut = false;
      logical_font.lfCharSet = ANSI_CHARSET;
      logical_font.lfOutPrecision = OUT_DEFAULT_PRECIS;
      logical_font.lfClipPrecision = CLIP_DEFAULT_PRECIS;
      logical_font.lfQuality = PROOF_QUALITY;
      logical_font.lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE;
      lstrcpy(logical_font.lfFaceName, fontname.c_str()); 

      font = CreateFontIndirect(&logical_font);

      HFONT previous_font = (HFONT)SelectObject(c, font);

      wglUseFontBitmaps(c, 0, 128, next_call_list_start);
      font_size_lookup[in_size] = next_call_list_start;
      font_handle_lookup[in_size] = font;
      next_call_list_start += 130;

      SelectObject(c, previous_font);
   }

#else

   // TODO: is this sufficient?
   point_size = size;

   if (font_size_lookup[size] == 0)
   {
      int list_start = glGenLists(128);

      // MACNOTE: Force Trebuchet MS.  It's what we mostly use anyway, but
      // I want to be sure they have it.
      const CFStringRef font_name = CFSTR("Trebuchet MS");
      
      ATSFontFamilyRef font = ATSFontFamilyFindFromName(font_name, kATSOptionFlagsDefault);
      if (!font) throw PianoGameError(WSTRING(L"Couldn't get ATSFontFamilyRef for font '" << WideFromMacString(font_name) << L"'."));         
      
      AGLContext context = aglGetCurrentContext();
      if (!context) throw PianoGameError(L"Couldn't retrieve OpenGL context while creating font.");         
      
      GLboolean ret = aglUseFont(context, font, normal, size, 0, 128, list_start);
      if (ret == GL_FALSE) throw PianoGameError(WSTRING(L"aglUseFont() call failed with error code: " << aglGetError()));
      
      font_size_lookup[size] = list_start;


      // Create the ATSU style object that we'll use for calculating text extents and store it for later.
      ATSUStyle style;

      OSStatus status = ATSUCreateStyle(&style);
      if (status != noErr) throw PianoGameError(WSTRING(L"Couldn't create ATSU style.  Error code: " << static_cast<int>(status)));

      Fixed fixed_size = Long2Fix(size);
      
      ATSUAttributeTag tags[] = { kATSUSizeTag };
      ByteCount sizes[] = { sizeof(Fixed) };
      ATSUAttributeValuePtr values[] = { &fixed_size };
      status = ATSUSetAttributes(style, sizeof(sizes) / sizeof(ByteCount), tags, sizes, values);
      if (status != noErr) throw PianoGameError(WSTRING(L"Couldn't set ATSU style attributes.  Error code: " << static_cast<int>(status)));
      
      atsu_style_lookup[size] = style;      
   }

#endif

}
Exemple #12
0
static int RLXAPI CreateSurface(int numberOfSparePages)
{
	static GLint          attrib[32];
	GLint		*pAttrib =  attrib;

	*pAttrib = AGL_RGBA; pAttrib++;
	*pAttrib = AGL_DOUBLEBUFFER; pAttrib++;
	*pAttrib = AGL_NONE; pAttrib++;

    AGLPixelFormat fmt;
    GLboolean      ok;

    g_pRLX->pGX->View.lpBackBuffer   = NULL;

    /* Choose an rgb pixel format */
    GDHandle gdhDisplay;
    ok = DMGetGDeviceByDisplayID((DisplayIDType)g_cgDisplayID, &gdhDisplay, false);
    SYS_ASSERT(ok == noErr);
    fmt = aglChoosePixelFormat(&gdhDisplay, 1, attrib);
	SYS_AGLTRACE(0);
    if(fmt == NULL)
    {
        ok = SYS_AGLTRACE(aglGetError());
		return -1;
    }
    /* Create an AGL context */
    g_pAGLC = aglCreateContext(fmt, NULL);
    SYS_AGLTRACE(0);
	if(g_pAGLC == NULL)
		return -2;

    /* Attach the window to the context */
    ok = SYS_AGLTRACE(aglSetDrawable(g_pAGLC, GetWindowPort(g_hWnd)));
    if(!ok)
		return -3;

    /* Make the context the current context */
    ok = SYS_AGLTRACE(aglSetCurrentContext(g_pAGLC));
    if(!ok)
		return -4;

	SizeWindow(g_hWnd, gl_lx, gl_ly, true);
	if ((g_pRLX->Video.Config & RLXVIDEO_Windowed))
		CenterWindow(g_hWnd);
    ShowWindow(g_hWnd);

	// copy portRect
	GetPortBounds(GetWindowPort(g_hWnd), g_pRect);

    /* Pixel format is no more needed */
    aglDestroyPixelFormat(fmt);

    if (!(g_pRLX->Video.Config & RLXVIDEO_Windowed))
    {
		HideMenuBar();
        aglSetFullScreen(g_pAGLC, 0, 0, 0, 0);
	    GLint swap = !!(g_pRLX->pGX->View.Flags & GX_CAPS_VSYNC);
        aglSetInteger(g_pAGLC, AGL_SWAP_INTERVAL, &swap);
		SYS_AGLTRACE(0);
	}

    // Reset engine
    GL_InstallExtensions();
	GL_ResetViewport();

	g_pRLX->pGX->Surfaces.maxSurface = numberOfSparePages;;

	if (g_pRLX->pGX->View.Flags & GX_CAPS_MULTISAMPLING)
	{
		glEnable(GL_MULTISAMPLE_ARB);
	}

    return 0;
}
Exemple #13
0
int  _glfwPlatformOpenWindow( int width, int height,
                              const _GLFWwndconfig *wndconfig,
                              const _GLFWfbconfig *fbconfig )
{
    OSStatus error;
    unsigned int windowAttributes;
    ProcessSerialNumber psn;

    // TODO: Break up this function!

    _glfwWin.windowUPP      = NULL;
    _glfwWin.mouseUPP       = NULL;
    _glfwWin.keyboardUPP    = NULL;
    _glfwWin.commandUPP     = NULL;
    _glfwWin.window         = NULL;
    _glfwWin.aglContext     = NULL;
    _glfwWin.aglPixelFormat = NULL;
    _glfwWin.cglContext     = NULL;
    _glfwWin.cglPixelFormat = NULL;

    _glfwWin.refreshRate = wndconfig->refreshRate;

    // Fail if OpenGL 3.0 or above was requested
    if( wndconfig->glMajor > 2 )
    {
        fprintf( stderr, "OpenGL 3.0+ is not yet supported on Mac OS X\n" );

        _glfwPlatformCloseWindow();
        return GL_FALSE;
    }

    if( _glfwLibrary.Unbundled )
    {
        if( GetCurrentProcess( &psn ) != noErr )
        {
            fprintf( stderr, "Failed to get the process serial number\n" );

            _glfwPlatformCloseWindow();
            return GL_FALSE;
        }

        if( TransformProcessType( &psn, kProcessTransformToForegroundApplication ) != noErr )
        {
            fprintf( stderr, "Failed to become a foreground application\n" );

            _glfwPlatformCloseWindow();
            return GL_FALSE;
        }

        if( wndconfig->mode == GLFW_FULLSCREEN )
        {
            if( SetFrontProcess( &psn ) != noErr )
            {
                fprintf( stderr, "Failed to become the front process\n" );

                _glfwPlatformCloseWindow();
                return GL_FALSE;
            }
        }
    }

    if( !installEventHandlers() )
    {
        fprintf( stderr,
                 "Failed to install Carbon application event handlers\n" );

        _glfwPlatformTerminate();
        return GL_FALSE;
    }

    // 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( wndconfig->mode == GLFW_WINDOW )
    {
        // create AGL pixel format attribute list
        GLint AGLpixelFormatAttributes[256];
        int numAGLAttrs = 0;

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

        if( fbconfig->stereo )
        {
            AGLpixelFormatAttributes[numAGLAttrs++] = AGL_STEREO;
        }

        _setAGLAttribute( AGL_AUX_BUFFERS,      fbconfig->auxBuffers);
        _setAGLAttribute( AGL_RED_SIZE,         fbconfig->redBits );
        _setAGLAttribute( AGL_GREEN_SIZE,       fbconfig->greenBits );
        _setAGLAttribute( AGL_BLUE_SIZE,        fbconfig->blueBits );
        _setAGLAttribute( AGL_ALPHA_SIZE,       fbconfig->alphaBits );
        _setAGLAttribute( AGL_DEPTH_SIZE,       fbconfig->depthBits );
        _setAGLAttribute( AGL_STENCIL_SIZE,     fbconfig->stencilBits );
        _setAGLAttribute( AGL_ACCUM_RED_SIZE,   fbconfig->accumRedBits );
        _setAGLAttribute( AGL_ACCUM_GREEN_SIZE, fbconfig->accumGreenBits );
        _setAGLAttribute( AGL_ACCUM_BLUE_SIZE,  fbconfig->accumBlueBits );
        _setAGLAttribute( AGL_ACCUM_ALPHA_SIZE, fbconfig->accumAlphaBits );

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

        AGLpixelFormatAttributes[numAGLAttrs++] = AGL_NONE;

        // create pixel format descriptor
        AGLDevice mainMonitor = GetMainDevice();
        _glfwWin.aglPixelFormat = aglChoosePixelFormat( &mainMonitor,
                                                        1,
                                                        AGLpixelFormatAttributes );
        if( _glfwWin.aglPixelFormat == NULL )
        {
            fprintf( stderr,
                     "Failed to choose AGL pixel format: %s\n",
                     aglErrorString( aglGetError() ) );

            _glfwPlatformCloseWindow();
            return GL_FALSE;
        }

        // create AGL context
        _glfwWin.aglContext = aglCreateContext( _glfwWin.aglPixelFormat, NULL );

        if( _glfwWin.aglContext == NULL )
        {
            fprintf( stderr,
                     "Failed to create AGL context: %s\n",
                     aglErrorString( aglGetError() ) );

            _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( wndconfig->windowNoResize )
        {
            windowAttributes |= kWindowLiveResizeAttribute;
        }
        else
        {
            windowAttributes |= ( kWindowFullZoomAttribute |
                                  kWindowResizableAttribute );
        }

        error = CreateNewWindow( kDocumentWindowClass,
                                 windowAttributes,
                                 &windowContentBounds,
                                 &( _glfwWin.window ) );
        if( ( error != noErr ) || ( _glfwWin.window == NULL ) )
        {
            fprintf( stderr, "Failed to create Carbon window\n" );

            _glfwPlatformCloseWindow();
            return GL_FALSE;
        }

        _glfwWin.windowUPP = NewEventHandlerUPP( windowEventHandler );

        error = InstallWindowEventHandler( _glfwWin.window,
                                           _glfwWin.windowUPP,
                                           GetEventTypeCount( GLFW_WINDOW_EVENT_TYPES ),
                                           GLFW_WINDOW_EVENT_TYPES,
                                           NULL,
                                           NULL );
        if( error != noErr )
        {
            fprintf( stderr, "Failed to install Carbon window event handler\n" );

            _glfwPlatformCloseWindow();
            return GL_FALSE;
        }

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

        if( !aglSetDrawable( _glfwWin.aglContext,
                             GetWindowPort( _glfwWin.window ) ) )
        {
            fprintf( stderr,
                     "Failed to set the AGL context as the Carbon window drawable: %s\n",
                     aglErrorString( aglGetError() ) );

            _glfwPlatformCloseWindow();
            return GL_FALSE;
        }

        // Make OpenGL context current
        if( !aglSetCurrentContext( _glfwWin.aglContext ) )
        {
            fprintf( stderr,
                     "Failed to make AGL context current: %s\n",
                     aglErrorString( aglGetError() ) );

            _glfwPlatformCloseWindow();
            return GL_FALSE;
        }

        ShowWindow( _glfwWin.window );
    }
    else
    {
        CGDisplayErr cgErr;
        CGLError cglErr;

        CFDictionaryRef optimalMode;

        GLint numCGLvs = 0;

        CGLPixelFormatAttribute CGLpixelFormatAttributes[64];
        int numCGLAttrs = 0;

        // variables for enumerating color depths
        GLint rgbColorDepth;

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

        if( fbconfig->stereo )
        {
            CGLpixelFormatAttributes[ numCGLAttrs++ ] = kCGLPFAStereo;
        }

        if( fbconfig->samples > 1 )
        {
            _setCGLAttribute( kCGLPFASamples,       (CGLPixelFormatAttribute)fbconfig->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)( fbconfig->accumRedBits \
                                                   + fbconfig->accumGreenBits \
                                                   + fbconfig->accumBlueBits \
                                                   + fbconfig->accumAlphaBits ) );

        _setCGLAttribute( kCGLPFAAlphaSize,   (CGLPixelFormatAttribute)fbconfig->alphaBits );
        _setCGLAttribute( kCGLPFADepthSize,   (CGLPixelFormatAttribute)fbconfig->depthBits );
        _setCGLAttribute( kCGLPFAStencilSize, (CGLPixelFormatAttribute)fbconfig->stencilBits );
        _setCGLAttribute( kCGLPFAAuxBuffers,  (CGLPixelFormatAttribute)fbconfig->auxBuffers );

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

        // create a suitable pixel format with above attributes..
        cglErr = CGLChoosePixelFormat( CGLpixelFormatAttributes,
                                       &_glfwWin.cglPixelFormat,
                                       &numCGLvs );
        if( cglErr != kCGLNoError )
        {
            fprintf( stderr,
                     "Failed to choose CGL pixel format: %s\n",
                     CGLErrorString( cglErr ) );

            _glfwPlatformCloseWindow();
            return GL_FALSE;
        }

        // ..and create a rendering context using that pixel format
        cglErr = CGLCreateContext( _glfwWin.cglPixelFormat, NULL, &_glfwWin.cglContext );
        if( cglErr != kCGLNoError )
        {
            fprintf( stderr,
                     "Failed to create CGL context: %s\n",
                     CGLErrorString( cglErr ) );

            _glfwPlatformCloseWindow();
            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( _glfwWin.cglPixelFormat,
                                      0,
                                      kCGLPFAColorSize,
                                      &rgbColorDepth );

        // capture the display for our application
        cgErr = CGCaptureAllDisplays();
        if( cgErr != kCGErrorSuccess )
        {
            fprintf( stderr,
                     "Failed to capture Core Graphics displays\n");

            _glfwPlatformCloseWindow();
            return GL_FALSE;
        }

        // find closest matching NON-STRETCHED display mode..
        optimalMode = CGDisplayBestModeForParametersAndRefreshRateWithProperty(
                            kCGDirectMainDisplay,
                            rgbColorDepth,
                            width,
                            height,
                            wndconfig->refreshRate,
                            NULL,
                            NULL );
        if( optimalMode == NULL )
        {
            fprintf( stderr,
                     "Failed to retrieve Core Graphics display mode\n");

            _glfwPlatformCloseWindow();
            return GL_FALSE;
        }

        // ..and switch to that mode
        cgErr = CGDisplaySwitchToMode( kCGDirectMainDisplay, optimalMode );
        if( cgErr != kCGErrorSuccess )
        {
            fprintf( stderr,
                     "Failed to switch to Core Graphics display mode\n");

            _glfwPlatformCloseWindow();
            return GL_FALSE;
        }

        // switch to our OpenGL context, and bring it up fullscreen
        cglErr = CGLSetCurrentContext( _glfwWin.cglContext );
        if( cglErr != kCGLNoError )
        {
            fprintf( stderr,
                     "Failed to make CGL context current: %s\n",
                     CGLErrorString( cglErr ) );

            _glfwPlatformCloseWindow();
            return GL_FALSE;
        }

        cglErr = CGLSetFullScreen( _glfwWin.cglContext );
        if( cglErr != kCGLNoError )
        {
            fprintf( stderr,
                     "Failed to set CGL fullscreen mode: %s\n",
                     CGLErrorString( cglErr ) );

            _glfwPlatformCloseWindow();
            return GL_FALSE;
        }
    }

    return GL_TRUE;
}
Exemple #14
0
/*****************************************************************************
  QGLContext AGL-specific code
 *****************************************************************************/
bool QGLContext::chooseContext(const QGLContext* shareContext)
{
    Q_D(QGLContext);
    d->cx = 0;
    d->vi = chooseMacVisual(0);
    if(!d->vi)
        return false;

    AGLPixelFormat fmt = (AGLPixelFormat)d->vi;
    GLint res;
    aglDescribePixelFormat(fmt, AGL_LEVEL, &res);
    d->glFormat.setPlane(res);
    if(deviceIsPixmap())
        res = 0;
    else
        aglDescribePixelFormat(fmt, AGL_DOUBLEBUFFER, &res);
    d->glFormat.setDoubleBuffer(res);
    aglDescribePixelFormat(fmt, AGL_DEPTH_SIZE, &res);
    d->glFormat.setDepth(res);
    if (d->glFormat.depth())
        d->glFormat.setDepthBufferSize(res);
    aglDescribePixelFormat(fmt, AGL_RGBA, &res);
    d->glFormat.setRgba(res);
    aglDescribePixelFormat(fmt, AGL_RED_SIZE, &res);
    d->glFormat.setRedBufferSize(res);
    aglDescribePixelFormat(fmt, AGL_GREEN_SIZE, &res);
    d->glFormat.setGreenBufferSize(res);
    aglDescribePixelFormat(fmt, AGL_BLUE_SIZE, &res);
    d->glFormat.setBlueBufferSize(res);
    aglDescribePixelFormat(fmt, AGL_ALPHA_SIZE, &res);
    d->glFormat.setAlpha(res);
    if (d->glFormat.alpha())
        d->glFormat.setAlphaBufferSize(res);
    aglDescribePixelFormat(fmt, AGL_ACCUM_RED_SIZE, &res);
    // Bug in Apple OpenGL (rdr://5015603), when we don't have an accumulation
    // buffer, it still claims that we have a 16-bit one (which is pretty rare).
    // So, we just assume we can never have a buffer that small.
    d->glFormat.setAccum(res > 5);
    if (d->glFormat.accum())
        d->glFormat.setAccumBufferSize(res);
    aglDescribePixelFormat(fmt, AGL_STENCIL_SIZE, &res);
    d->glFormat.setStencil(res);
    if (d->glFormat.stencil())
        d->glFormat.setStencilBufferSize(res);
    aglDescribePixelFormat(fmt, AGL_STEREO, &res);
    d->glFormat.setStereo(res);
    aglDescribePixelFormat(fmt, AGL_SAMPLE_BUFFERS_ARB, &res);
    d->glFormat.setSampleBuffers(res);
    if (d->glFormat.sampleBuffers()) {
        aglDescribePixelFormat(fmt, AGL_SAMPLES_ARB, &res);
        d->glFormat.setSamples(res);
    }

    if(shareContext && (!shareContext->isValid() || !shareContext->d_func()->cx)) {
        qWarning("QGLContext::chooseContext(): Cannot share with invalid context");
        shareContext = 0;
    }

    // sharing between rgba and color-index will give wrong colors
    if(shareContext && (format().rgba() != shareContext->format().rgba()))
        shareContext = 0;
    AGLContext ctx = aglCreateContext(fmt, (AGLContext) (shareContext ? shareContext->d_func()->cx : 0));
    if(!ctx) {
        GLenum err = aglGetError();
        if(err == AGL_BAD_MATCH || err == AGL_BAD_CONTEXT) {
            if(shareContext && shareContext->d_func()->cx) {
                qWarning("QGLContext::chooseContext(): Context sharing mismatch!");
                if(!(ctx = aglCreateContext(fmt, 0)))
                    return false;
                shareContext = 0;
            }
        }
        if(!ctx) {
            qWarning("QGLContext::chooseContext(): Unable to create QGLContext");
            return false;
        }
    }
    d->cx = ctx;
    if (shareContext && shareContext->d_func()->cx) {
        QGLContext *share = const_cast<QGLContext *>(shareContext);
        d->sharing = true;
        share->d_func()->sharing = true;
    }
    if(deviceIsPixmap())
        updatePaintDevice();

    // vblank syncing
    GLint interval = d->reqFormat.swapInterval();
    if (interval != -1) {
        aglSetInteger((AGLContext)d->cx, AGL_SWAP_INTERVAL, &interval);
        if (interval != 0)
            aglEnable((AGLContext)d->cx, AGL_SWAP_INTERVAL);
        else
            aglDisable((AGLContext)d->cx, AGL_SWAP_INTERVAL);
    }
    aglGetInteger((AGLContext)d->cx, AGL_SWAP_INTERVAL, &interval);
    d->glFormat.setSwapInterval(interval);
    return true;
}
Exemple #15
0
static AGLContext createContext(WindowRef window) {
    AGLPixelFormat pf;
    AGLContext ctx;
    GDHandle gdh;
    CFDictionaryRef refMode;
    GLenum error;

    CGDirectDisplayID mainDisplay = CGMainDisplayID();

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

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

    g_Window.double_buffered = true;

    if (!g_Window.fs) {
        pf = aglChoosePixelFormat(NULL, 0, attrs);
    } else {
        CGDisplayCapture(mainDisplay);
        refMode = CGDisplayBestModeForParameters(mainDisplay, 32,
                                                 g_Window.width, g_Window.height, NULL);
        CGDisplaySwitchToMode(mainDisplay, refMode);
        DMGetGDeviceByDisplayID(mainDisplay, &gdh, false);
        pf = aglChoosePixelFormat(&gdh, 1, fullscreen_attrs);

        error = aglGetError();
        if (error != AGL_NO_ERROR) {
            printf("%s\n", aglErrorString(error));
            return 0;
        }
    }

    if (!pf) {
        printf("Error choosing pixel format\n");
        return 0;
    }

    ctx = aglCreateContext(pf, 0);
    if (!ctx) {
        printf("%s\n", aglErrorString(aglGetError()));
        return 0;
    }

    aglDestroyPixelFormat(pf);
    aglSetCurrentContext(ctx);

    if (g_Window.fs) {
        aglSetFullScreen(ctx, g_Window.width, g_Window.height, 0, 0);
    } else {
        aglSetWindowRef(ctx, window);
    }

    return ctx;
}