deblocker
deblocker

Reputation: 7697

JavaScript conversion to Float32Array and back for WebGL readPixels

I am storing id (which is a value comprised in 24bit-range) into an Float32Array(3) for latter retrieval in WebGL:

var r = 0, 
    g = 0, 
    b = id;
if (b >= 65536) { 
    r = ~~(b / 65536);
    b -= r * 65536; 
}
if (b >= 256) { 
    g = ~~(b / 256); 
    b -= g * 256;
}
var fa = new Float32Array([r/255, g/255, b/255]);

For the sake of completeness, here is how i am using that value:

gl.uniform3fv(uniforms['u_id'], fa);

...and this is how i get my id back from WebGLRenderingContext.readPixels():

var result = new Uint8Array(4);
gl.readPixels(x, y, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, result);
var id = result[0] << 16 | result[1] << 8 | result[2];

Which is the correct way to split that value into my Float32Array? I strongly believe that such task could be accomplished in a more efficient and elegant way (actually, what i am doing is working but is really hurting my eyes).

Upvotes: 0

Views: 150

Answers (1)

user555045
user555045

Reputation: 64904

id has a form like this:

0000 0000 rrrr rrrr gggg gggg bbbb bbbb

A part (r, g or b) can be extracted by putting it in the lowest byte and masking the rest away. Sometimes one of those steps is unnecessary. So:

b = id & 255  // b is already in the low byte, so no shift
g = (id >> 8) & 255
r = id >> 16  // no mask because there is nothing "above" r

This can be put together with the division and putting it in an array:

[(id >> 16) / 255, ((id >> 8) & 255) / 255, (id & 255) / 255]

Upvotes: 1

Related Questions