PDA

View Full Version : Converting 32 float to 4 byte equivalents... or something like that....



CelticDaddio
08-10-2006, 08:39 PM
I want to calculate the distance from the viewpoint/eyepoint to each vertex in my scene then store that value in the r,g,b and a components of a RGBA8 texture.... I have gone round in circles trying to figure out how to go from a single 32 bit number to 4 - 8bit numbers. Is the following reasonable? That is... should it work? If not, does anyone know what would?

Fragment Shader:


// Calculate Distance To Each Vertex from vertex position
// in eyespace passed as varying from vertex shader
float distance = length(eyepoint);

// convert distance from floating point to fixed point
// with 8 fractional bits
float fixedPointDistance = distance * pow(2, 8);

// get upper 16 bits
int upper16Bits = int(fixedPointDistance/65536);

// get lower 16 bits
int lower16Bits = int(fixedPointDistance);

// get byte1 (or bits 23-31)
int byte1 = int(upper16Bits/256);

// get byte2 (or bits 16-23)
int byte2 = int(upper16Bits*256)/256);

// get byte3 (or bits 8-15)
int byte3 = int(lower16Bits/256);

// get byte1 (or bits 0-7)
int byte4 = int(lower16Bits*256)/256);

float red = float(byte1/256);
float green = float(byte2/256);
float blue = float(byte3/256);
float alpha = float(byte4/256);

gl_FragColor = vec4(red, green, blue, alpha);CD

glAren
08-11-2006, 07:34 AM
Seems right, you shlould be also able to use bite-shift operators ">>" and "<<".

CelticDaddio
08-11-2006, 07:52 AM
I wish, but bit shifts are not supported in GLSL.

CD


Originally posted by glAren:
... you shlould be also able to use bite-shift operators ">>" and "<<".

SiW
08-11-2006, 03:26 PM
There's an example on codesampler.com using such a procedure to pack a 24-bit value into RGB channels. Look for the "shadow map with FBO" example.

sqrt[-1]
08-11-2006, 06:39 PM
I seem to recall this demo doing that in the fragment shader for lighting depth buffers:

http://www.delphi3d.net/download/portalengine.zip

glAren
08-13-2006, 02:02 AM
Originally posted by CelticDaddio:
I wish, but bit shifts are not supported in GLSL.

CD
You are right, its reserved for the future use in spec.

Jedimaster
09-16-2006, 07:50 PM
Why not pre computed these datas stores to a texture ? it's too expensive for shaders.

look at the glslspec,in next generation it will add more operator, more and more like c++,even TEMPLATE