# WebGL color quantization

I'm making a WebGL game in a 90s DOS games style. I'm trying to use a shader which would quantize colors to get reduced colors look. I found this solution: Palette reduction to pre-defined palette, however I only get 4 colors when I apply the shader (as in the picture). Any help would be greatly appreciated.

• You want the code of the other question giving an output of only 4 colours, is that it? Nov 14, 2015 at 16:33
• I get only 4 colors, but I would like to get 256. I edited the question.
– Nvs
Nov 14, 2015 at 16:34
• Could you edit to clarify what code you're using, and what it's intended to do? Have you tried debugging the problem, and if so, how?
– Anko
Nov 19, 2015 at 1:41

Unless you have a specific 256 colors palette in mind, you could just use the "8-bit truecolor" as described at 8-bit color Wikipedia page.

To do that, you need to map R and G channels onto 8 values (3 bits each), and B onto 4 values (2 bits). Those 8 bits together make up 256 possible colors.

Provided your gl_FragColor is already determined, the lines below will map its color to one of 256 values:

vec3 color_resolution = vec3(8.0, 8.0, 4.0);
vec3 color_bands = floor(gl_FragColor.rgb * color_resolution) / (color_resolution - 1.0);
gl_FragColor = vec4(min(color_bands, 1.0), gl_FragColor.a);


The min clamping in the last line might not be necessary, this depends on the color buffer's format, you might keep it if unsure or take a look at https://stackoverflow.com/questions/26786711/will-the-fragment-shader-automatically-clamp-the-color-value-to-its-range.

• Note that this code does not minimise the color difference with the original pixel. Another formula which does is: floor(gl_FragColor.rgb * (color_resolution - 1.0) + 0.5) / (color_resolution - 1.0);. In a perfect world you would also have to perform gamma correction before quantisation. Apr 15, 2016 at 14:40