繁体   English   中英

GLKit,Opengl ES 3.0,使用 glReadPixels 获取深度

[英]GLKit, Opengl ES 3.0, get depth with glReadPixels

我可以在屏幕上获得距离点吗? 这是代码:

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES3];

    if (!context || ![EAGLContext setCurrentContext:context]) {
        NSLog(@"Failed to create ES context");
    }

    GLKView *view = (GLKView *)self.view;
    view.context = context;
    view.drawableDepthFormat = GLKViewDrawableDepthFormat16;

    glEnable(GL_DEPTH_TEST);

    shader = [[BaseEffect alloc] initWithVertexShader:@"Shader.vsh"
                                       fragmentShader:@"Shader.fsh"];

    // setup projection and model matrix
}

- (void)glkView:(GLKView *)view drawInRect:(CGRect)rect
{
    glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
    glClearDepthf(1.0f);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);


    [shader prepareToDraw];
    // draw point

    glBindVertexArray(vertexArray);
    glDrawArrays(GL_POINTS, 0, pointsCount);
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint tapLoc = [touch locationInView:self.view];

    GLfloat depth = 0;
    glReadPixels(tapLoc.x, tapLoc.y, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &depth);
    NSLog(@"Depth %f", depth);
}

一切都完美地绘制,但我无法获得绘制点的距离。

编辑:

我记录深度,也尝试颜色。 Color 仅读取此参数:

glReadPixels(p.x, p.y, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, pixelBuffer);

使用 GL_FLOAT 时,无法读取 rgb。 我也尝试在绘制后获取值:

- (void)glkView:(GLKView *)view drawInRect:(CGRect)rect
{
    // preparing and drawing

    if (testDepthPoint.x != 0) {
        [self testDepth:testDepthPoint];
        testDepthPoint = CGPointZero;
    }
}

- (void)testDepth:(CGPoint)p {
    GLfloat depth = -99.0;
    glReadPixels(p.x, p.y, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &depth);
    NSLog(@"Depth %f", depth); // always log -99.0
}

不适合我

除了您应该查看depth而不是pixelColor的事实pixelColor ,您还需要注意时间,它应该在帧完成绘制之后和下一帧提交之前。

不支持 OpenGL ES 2.0 从缓冲区读取GL_DEPTH_COMPONENT 更多信息在这里:

https://stackoverflow.com/a/18805281/820795

它适用于 Opengl ES 3.0

在 ES 3.0 及更高版本中,支持深度纹理。 使用它,您可以使用以下步骤获得深度。

  • 将场景渲染到 FBO,使用纹理作为深度附件。
  • 使用着色器渲染屏幕大小的四边形,该着色器对上一步中生成的深度纹理进行采样,并将值写入颜色缓冲区。
  • 在颜色缓冲区上使用 glReadPixels()。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM