1

我正在尝试OpenGL使用深度缓冲区创建上下文Core OpenGl。然后我希望通过CAOpenGLLayer. 从我读过的内容看来,我应该能够通过以下方法创建所需的上下文:

我在接口中声明了以下实例变量

@interface TorusCAOpenGLLayer : CAOpenGLLayer
{
    //omitted code
    CGLPixelFormatObj pix;
    GLint pixn;
    CGLContextObj ctx;
} 

然后在我覆盖的实现copyCGLContextForPixelFormat中,我认为应该创建所需的上下文

- (CGLContextObj)copyCGLContextForPixelFormat:(CGLPixelFormatObj)pixelFormat
{
    CGLPixelFormatAttribute attrs[] = 
    {
        kCGLPFAColorSize,     (CGLPixelFormatAttribute)24,
        kCGLPFAAlphaSize,     (CGLPixelFormatAttribute)8,
        kCGLPFADepthSize,     (CGLPixelFormatAttribute)24,
        (CGLPixelFormatAttribute)0
    };

    NSLog(@"Pixel format error:%d", CGLChoosePixelFormat(attrs, &pix, &pixn)); //returns 0

    NSLog(@"Context error: %d", CGLCreateContext(pix, NULL, &ctx)); //returns 0

    NSLog(@"The context:%p", ctx); // returns same memory address as similar NSLog call in function below

   return ctx;
}

最后我重写drawInCGLContext以显示内容。

-(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, &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];
}

该程序编译良好并显示内容,但没有深度测试。我需要做些什么才能让它工作吗?还是我的整个方法都错了?

4

1 回答 1

1

看起来我覆盖了错误的方法。要获得所需的深度缓冲区,应覆盖copyCGLPixelFormatForDisplayMask类似的内容:

- (CGLPixelFormatObj)copyCGLPixelFormatForDisplayMask:(uint32_t)mask {
    CGLPixelFormatAttribute attributes[] =
    {
        kCGLPFADepthSize, 24,
        0
    };
    CGLPixelFormatObj pixelFormatObj = NULL;
    GLint numPixelFormats = 0;
    CGLChoosePixelFormat(attributes, &pixelFormatObj, &numPixelFormats);
    if(pixelFormatObj == NULL)
        NSLog(@"Error: Could not choose pixel format!");
return pixelFormatObj;
}

基于这里的代码。

于 2012-11-09T04:55:22.293 回答