Bitpacking into buffers with webgl (shadertoy) I'm working on a webgl pixel shader which is writing to a 16 bit floating point buffer (each color channel r,g,b,a is a 16 bit floating point number).

I'm trying to figure out if there are any decent ways to pack the following info into those 16 bits per color channel:


normal (x,y,z where z is always negative)
uv coordinates (x,y between 0 and 1)
material index (an integer. 0 to 3 would be plenty)
distance (a positive float)


I could live without distance if needed but the others are required.

I know that I can store just x,y of the normal and calculate z as needed since its always negative (the normal is in screenspace).

That still leaves 5 values to store in four 16 bit floats: normal.xy, uv.xy, material index.

Does anyone have any good methods for making this happen? It would be nice to have the distance too, otherwise I am limited to directional lighting instead of getting point lights as well.

This is in shadertoy if that context changes any answers.

I'll be sampling this buffer with nearest neighbor sampling, so you don't have to worry about it being stored in a way that interpolates well.

Thanks!
Assuming you are not going to filter the buffer using HW texture filtering: since you only need 4 values for the material index, pack it in the sign bits of uv x and y.