Skip to content

Instantly share code, notes, and snippets.

@uncommoncode
Last active December 9, 2020 13:27
Show Gist options
  • Save uncommoncode/600b9cd324d1a736c8a8 to your computer and use it in GitHub Desktop.
Save uncommoncode/600b9cd324d1a736c8a8 to your computer and use it in GitHub Desktop.
Stuff a 3 component vector into a single floating point component.
/*
* The number of bits of precision per color channel are log_2(c_precision),
* in this case 7 bits per color, or 21 bits total.
*
* A c_precision of 128 fits within 7 base-10 digits.
*
* NOTE: an IEEE 754 float can only express 7 digits exactly for all digits.
*/
const float c_precision = 128.0;
const float c_precisionp1 = c_precision + 1.0;
/*
* \param color normalized RGB value
* \returns 3-component encoded float
*/
float color2float(vec3 color)
color = clamp(color, 0.0, 1.0);
return floor(color.r * c_precision + 0.5)
+ floor(color.b * c_precision + 0.5) * c_precisionp1
+ floor(color.g * c_precision + 0.5) * c_precisionp1 * c_precisionp1;
}
/*
* \param value 3-component encoded float
* \returns normalized RGB value
*/
vec3 float2color(float value) {
vec3 color;
color.r = mod(value, c_precisionp1) / c_precision;
color.b = mod(floor(value / c_precisionp1), c_precisionp1) / c_precision;
color.g = floor(value / (c_precisionp1 * c_precisionp1)) / c_precision;
return color;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment