0

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).

8
  • What are the definitions of "efficient" and "elegant" at Question? Commented Nov 10, 2017 at 6:33
  • If b is greater than 65536 at if (b >= 65536) { b would also be greater than 256 at next line at if (b >= 256) { , yes? Commented Nov 10, 2017 at 6:38
  • @guest271314 correct, this is how it is meant. i hadn't time to make it better in the past, i am trying now to restyle that ugly (but working) piece of code Commented Nov 10, 2017 at 6:39
  • 1
    What is this supposed to do? If you're just storing the first second and third bytes, that's trivial with bit-manipulation. Commented Nov 10, 2017 at 11:52
  • 1
    Here try this [(id >> 16) / 255, ((id >> 8) & 255) / 255, (id & 255) / 255] Commented Nov 10, 2017 at 15:46

1 Answer 1

1

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]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.