Created
April 19, 2019 08:03
-
-
Save orlp/7c07706a6611730b22cafebf742193be to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Original idea by Mikkel Gjoel (https://computergraphics.stackexchange.com/a/5952/10515), | |
// simplified to one readable function. | |
// Demo at https://www.shadertoy.com/view/Wts3zH. | |
// Dithers and quantizes color value c in [0, 1] to the given color depth. | |
// It's expected that rng contains a uniform random variable on [0, 1]. | |
uint dither_quantize(float c, uint depth, float rng) { | |
float cmax = float(depth) - 1.0; | |
float ci = c * cmax; | |
float d; | |
if (ci < 0.5 || ci >= cmax - 0.5) { | |
// Uniform distribution on [-0.5, 0.5] for edges. | |
d = rng - 0.5; | |
} else { | |
// Symmetric triangular distribution on [-1, 1]. | |
d = (rng < 0.5) ? sqrt(2.0 * rng) - 1.0 : 1.0 - sqrt(2.0 - 2.0*rng); | |
} | |
return uint(clamp(ci + d + 0.5, 0.0, cmax)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment