简体   繁体   中英

Return floats from fragmentshader

For an application I need to create a depth-image of a mesh. Basically I want a image, where each pixel tells the distance between the camera center and the intersection point. I choose to do this task with OpenGL, so that most of the computation can be done on the GPU instead of the CPU.

Here is my code for the vertex-shader. It computes the real-world coordinate of the intersection point and stores the coordinates in a varying vec4 , so that I have access to it in the fragment-shader.

varying vec4 verpos;
void main(void)
{
    gl_Position = ftransform();
    verpos = gl_ModelViewMatrix*gl_Vertex;
}

And here the code for the fragment-shader. In the fragment-shader I use these coordinates to compute the eulidean distance to the origin (0,0,0) using pythagoras. To get access to the computed value on the CPU, my plan is to store the distance as a color using gl_FragColor , and extract the color values using glReadPixels(0, 0, width, height, GL_RED, GL_FLOAT, &distances[0]);

varying vec4 verpos;
void main() 
{ 
    float x = verpos.x;
    float y = verpos.y;
    float z = verpos.z;

    float depth = sqrt(x*x + y*y + z*z) / 5000.0;
    gl_FragColor = vec4(depth, depth, depth, 1.0);
}

The problem is, that I receive the results only in the precision of 0.003921569 ( =1/255 ). The resulting values contain for instance 0.364705890, 0.364705890, 0.364705890, 0.364705890, 0.368627459, 0.368627459, 0.368627459 . Most of the values in a row are exactly the same, and then there is a jump of 1/255. So somewhere inbetween gl_FragColor and glReadPixels OpenGL converts the floats to 8 bits and afterwards converts them back to float.

How can I extract distance-values as float without loosing precision?

Attach a R32F or R16F texture to a FBO and render to it. Then extract the pixels with glGetTexImage2D() like you would do with glReadPixels() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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