shapeare
shapeare

Reputation: 4233

Read vertex color from screen space

For some reason, I need to know the color of the vertices of an object. The way I can think of is to render the vertex to the screen and then call glReadPixels to fetch the color of the vertices from screen space.

My program is implemented as follows:

  1. Render the ith vertex:

    glPointSize(8.0);
    glDrawArrays(GL_POINTS, i, 1);
    
  2. Compute the screen coordinates of this vertex:

    oPos[3] = 1.0
    // assume the object space coordinates of the vertex is oPos.
    

    multiply oPos by the model-view-projection matrix to get the normalized device coordinates of this vertex, denoted as ndcPos;

    ndcPos[1~3] /= ndcPos[3]
    

    finally, multiply ndcPos with the viewport matrix to get the screen coordinates, denoted as screenPos. The viewport matrix is defined as:

    GLfloat viewportMat[] = {
        screen_width/2, 0, 0, 0,
        0, screen_height/2, 0, 0,
        0, 0, 1, 0,
        (screen_width-1)/2.0, (screen_height-1)/2.0, 0, 1};
    
  3. Finally, call glReadPixels as:

    glReadPixels(int(screenPos[0]+0.5), int(screenPos[1]+0.5),
        1, 1, GL_RGB, GL_FLOAT, currentColor);
    

    The resulting color will then be stored at currentColor, which is a vector of length three.

My questions are:

  1. Is there any better ways to get the vertex color rather than query them from screen space?
  2. Any ideas about the correctness of my second and third step?

Upvotes: 1

Views: 85

Answers (1)

Wyzard
Wyzard

Reputation: 34563

OpenGL transform feedback allows a shader to write arbitrary values into a buffer object, which can then be read by the host program. You can use this to make your vertex shader pass the computed vertex colors back to the host program.

The nice thing about transform feedback is that you can use it while drawing to the screen, so you can draw your geometry and capture the vertex colors in a single pass. Or, if you prefer, you can draw the geometry with rasterization turned off to capture the feedback data without touching the screen.

Since the data produced by transform feedback is stored in a buffer object, you can use it as input for other drawing operations, too. Depending on what you plan to do with the computed vertex colors, you may be able to avoid transferring them back to the host program at all.

Upvotes: 2

Related Questions