title: Using Core OpenGL to programmatically create a context with depth buffer: What am I doing wrong?
body: <p>I'm trying to create an <code>OpenGL</code> context with depth buffer using <code>Core OpenGl</code>. I then wish to display the OpenGL content via a <code>CAOpenGLLayer</code>. From what I've read it seems I should be able to create the desired context by the following method:</p>
  
  <p>I declare the following instance variable in the interface</p>
  
  <pre><code>@interface TorusCAOpenGLLayer : CAOpenGLLayer
  {
      //omitted code
      CGLPixelFormatObj pix;
      GLint pixn;
      CGLContextObj ctx;
  } 
  </code></pre>
  
  <p>Then in the implementation I override <code>copyCGLContextForPixelFormat</code>, which I believe should create the required context</p>
  
  <pre><code>- (CGLContextObj)copyCGLContextForPixelFormat:(CGLPixelFormatObj)pixelFormat
  {
      CGLPixelFormatAttribute attrs[] = 
      {
          kCGLPFAColorSize,     (CGLPixelFormatAttribute)24,
          kCGLPFAAlphaSize,     (CGLPixelFormatAttribute)8,
          kCGLPFADepthSize,     (CGLPixelFormatAttribute)24,
          (CGLPixelFormatAttribute)0
      };
  
      NSLog(@"Pixel format error:%d", CGLChoosePixelFormat(attrs, &amp;pix, &amp;pixn)); //returns 0
  
      NSLog(@"Context error: %d", CGLCreateContext(pix, NULL, &amp;ctx)); //returns 0
  
      NSLog(@"The context:%p", ctx); // returns same memory address as similar NSLog call in function below
  
     return ctx;
  }
  </code></pre>
  
  <p>Finally I override <code>drawInCGLContext</code> to display the content.</p>
  
  <pre><code>-(void)drawInCGLContext:(CGLContextObj)glContext pixelFormat:    (CGLPixelFormatObj)pixelFormat forLayerTime:(CFTimeInterval)timeInterval displayTime:(const CVTimeStamp *)timeStamp
  {
      // Set the current context to the one given to us.
      CGLSetCurrentContext(glContext);
  
      int depth;
  
      NSLog(@"The context again:%p", glContext); //returns the same memory address as the NSLog in the previous function
  
      glMatrixMode (GL_PROJECTION);
      glLoadIdentity ();
      glOrtho(0.5, 0.5, 1.0, 1.0, -1.0, 1.0);
  
      glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
      glEnable(GL_DEPTH_TEST);
  
      glGetIntegerv(GL_DEPTH_BITS, &amp;depth);
      NSLog(@"%i bits depth", depth); // returns 0
  
      glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  
      //drawing code here
  
      // Call super to finalize the drawing. By default all it does is call glFlush().
      [super drawInCGLContext:glContext pixelFormat:pixelFormat forLayerTime:timeInterval displayTime:timeStamp];
  }
  </code></pre>
  
  <p>The program compiles fine and displays the content, but without the depth testing. Is there something extra I have to do to get this to work? Or is my entire approach wrong?</p>