Packing a float into an RGB-value

Hi there

I´d like to write gl_FragCoord.z into gl_FragColor. gl_FragColor targets the framebuffer (32 Bit RGBA). Of course i´d like to get the full precision of gl_FragCoord.z, so i need a way to “pack” it into the color.

However i couldn´t find any packing-function in the glsl-spec. I am not sure, but if i recall correctly, ARB_fp had such a function, no?

Bitshifts aren´t supported yet, either.

So, how could i do that?


Why not create a floating point target?

No, there wasn’t any packing/unpacking in ARB-fp, only NV-fp had it.

In NV-fp, the packing/unpacking is limited. There is no 32 bit float -> RGBA8 and vice-versa.

Take a look at Tom’s portal rendering demo
He’s packing a float into RGBA cubemap(via shifting) for shadow mapping. It’s pretty easy.

Great, that was exactly that kind of trick i was looking for.

However, i don´t understand how it really works.

I have a float, to be exactly a depth-value, which is between 0 and 1. Say it would be 0.5;

Tom does this:
PARAM pack = { 1, 256, 65536, 16777216 };

Squeeze the length into an RGB color.

MUL len, len, pack;
FRC result.color, len;

However, after the mul, i would have the values
{0.5, 128, 32768, 8388608}

And after the fraction, i would get
{0.5, 0, 0, 0}

So now, i am where i was at the beginning. I want to represent 0.5 with 32 bit precision, but it only gets put into the red-value, with 8 Bit precision.

I will take a look into this method, maybe i am able to get this working myself, since i got the general idea now, but i assume, that Tom´s shader is not supposed to work with [0,1] ranged values, but with greater values.

So, if anyone can give me even more hints, that would be cool.


To represent 0.5, you doesn’t need 32bit precision, as =.5 is 0.1 binary written. So you get something like 0.10000000000000000000000000000000 :smiley: You are practically shifting each 8-bit portiaon of float into 4 registers(throught multiplication). The FRC instruction is to “clean” the rests. Important: this method will word only with numbers from 0 to 1!

This topic was automatically closed 183 days after the last reply. New replies are no longer allowed.