BLOG

Notes from the KAYAC hyper-casual team

Rethinking 16-Bit Color

Takashi Hirayama

Comparison of 565, 565 with dithering, 4444 and 4444 with dithering

Hello. I'm Hirayama from the Technology Department.

I wrote an article about indexed color (palettes) before, and this time I'd like to write about an even more primitive form of compression: converting to 16-bit color.

Even I wonder why I'm bringing this up now that ETC2 and ASTC have made it far less common. But our company has long-running products, and there are cases where moving to ETC2 or ASTC is difficult. Also, the simple color reduction I'm introducing here is used as a foundation in ETC2 and ASTC too, so it doesn't hurt to know its characteristics.

Let me state the conclusions up front.

  • If ETC2 will do, you don't need the rest of this
  • If you can put up with the effort and load of palettizing, that's usually better in both quality and size
  • Unity's built-in 16-bit conversion doesn't seem very good, so I made a custom importer

The code is on GitHub. For comparing image quality, there's also a ready-to-run WebGL build.

The Unity version used in this article is 2018.3.1.

Two kinds of 16-bit color

Unity supports two kinds of 16-bit color.

One is ARGB4444, which gives 4 bits (16 levels) each to red, green, blue and alpha, and the other is RGB565, which gives 5 bits (32 levels) to red, 6 bits (64 levels) to green and 5 bits to blue, with no alpha. From here on I'll call them "4444" and "565" for short.

How many bits the alpha channel needs depends on the case, so this time I'll ignore the alpha channel and look only at RGB image quality.

Gradients in 8888, 565 and 4444

The left is uncompressed 8888 (RGBA32). This clean gradient looks slightly stepped in 565, in the middle. If you can't see it, lucky you; don't worry about it. With 256 levels each for R, G and B, you can use as many as 16.77 million colors. With 565, that drops to 65 thousand. For an image close to black and white, like this example, what was 256 levels drops to 32 to 64 levels. As a result, it gets pretty ugly.

And the right is 4444, with only 4096 RGB colors, and just 16 levels for black and white. The steps are plainly visible.

Let's also look at a colored picture that isn't black and white.

A colored picture in 8888, 565 and 4444

In this case you can hardly see any degradation with 565, but with 4444 you can see that the boundaries between colors are a mess.

How color reduction actually works

So what does "turning 8 bits into 4 bits" actually involve? To make it easy to follow, let's look at it in decimal first.

The problem when restoring

Say there were originally 100 levels. Let's drop that to 10 levels, 0 to 9. The easy way is to take just the tens digit. 86→8, 74→7, and so on.

Then how do you restore the original two digits from the data reduced to one digit?

Multiplying by 10 turns 8 into 80, but that doesn't work well. You can see why if you think about compressing 99, pure white. 99 becomes 9, and if you turn that into 90 when restoring, pure white doesn't come back as pure white. Not being able to represent white is a bit of a problem.

It works better if you "put the same digit in the ones place as in the tens place".

For example, when restoring 9 to two digits, put two 9s side by side to make 99. That gives white. Turn 8 into 88, 7 into 77 and so on, and 0 becomes 0, so "black stays black and white stays white".

The problem of error

When you reduce the original two digits to one and then restore it to two, how far off from the original value does it end up? I'll call the size of this discrepancy the "error".

For example, if 99 becomes 9, it's restored to 99, so the error is 0. If 90 becomes 9, that also becomes 99, so the error is 9.

We want to compress so that the error is as small as possible. In this example, if 90 became 8 instead of 9, it would become 88, so the error would be 2. In other words, simply taking the tens digit doesn't give the optimal result.

Minimizing the error

If you think of it as compressing the range 0 to 99 into the range 0 to 9, it's simple. Think about the "width", the maximum minus the minimum. The original width is 99-0, which is 99, and after compression it's 9-0, which is 9, so we're compressing a width of 99 into a width of 9. So we divide by (99/9)=11. The trick is to do this with fractional numbers, not integers.

Now 99, for example, becomes exactly 9, and 90 becomes 8.18... Rounding then takes it to whichever is closer. In a program, rounding is "add 0.5 and then truncate", so in code it looks like this:

compressed = Mathf.FloorToInt((original / (99f / 9f)) + 0.5f);

The maximum error is 5. For example, 94 is 94/11=8.545..., so it's rounded to 9, and restored it becomes 99, an error of 5. If you simply truncated the ones digit, the maximum error would be 9, as 90 becomes 99, so this is a big improvement.

Writing the expression for real colors

I used decimal to keep things simple, but the real thing is binary. We convert values from 0 to 255 into 0 to 15 for 4 bits, 0 to 31 for 5 bits, and 0 to 63 for 6 bits.

In decimal, 99 became 9, and when restoring we copied it into the ones place to get 99; it's the same in binary.

For example, if binary 11111111 (255=0xff) is compressed to 1111 (15=0xf), when restoring we append the same 4 digits at the bottom to get 11111111.

If 101011111 (175=0xaf) is, say, compressed to 1010 (10=0xa), when restoring we append the top 4 digits, 1010, at the bottom to get 10101010 (170=0xaa).

It's the same with 5 bits: 10101 is expanded to 10101101 by attaching the top 3 bits at the bottom, and with 6 bits, 110011 is expanded to 11001111 by attaching the top 2 bits at the bottom. This way, white comes back as white and black as black.

I don't know if every GPU does this, but on a GPU that didn't, white wouldn't come back as white, so I think this is probably the norm. For example, 0xf becomes 0xff, 0xe becomes 0xee, and 0x8 becomes 0x88.

So what does the calculation look like? It's actually almost the same as in decimal.

compressed4bit = Mathf.FloorToInt((original / (255f / 15f)) + 0.5f);
compressed5bit = Mathf.FloorToInt((original / (255f / 31f)) + 0.5f);
compressed6bit = Mathf.FloorToInt((original / (255f / 63f)) + 0.5f);

You just replace (99f/9f) with (255f/15f) or (255f/31f).

Think of original as a variable holding 0 to 255, for example an element of type Color32 obtained with Texture2D.GetPixels32(). You divide it so the maximum is 15, 31 or 63, add 0.5, and truncate to an integer. Simple truncation gives an error of up to 15 with 4 bits (0xf0=240 becomes 255), but this way the maximum error is 8 (0xf7=247 becomes 255).

You can also do it all in integers, without going through a cast to float.

compressed4bit = ((original * (15 * 2)) + 255) / (255 * 2);
compressed5bit = ((original * (15 * 2)) + 255) / (255 * 2);
compressed6bit = ((original * (15 * 2)) + 255) / (255 * 2);

Dividing by 255/15 is the same as multiplying by 15 and then dividing by 255. When calculating in integers, the division has to come last, so adding 0.5 has to happen before the division. You bring everything to the common denominator (255*2)=510: adding 255 and then dividing by 510 amounts to adding 0.5. There's no guarantee that integers are faster, though.

If you want to speed up the integer version, dividing by 512 instead of 510 shifts the results slightly, but gets you almost the same results faster (dividing by 512 can be done with a 9-bit right shift). The sample doesn't go that far.

Compared with truncation

My own conversion vs. Unity's ARGB16 import

The left was converted to 16-bit with my own implementation of the processing above, and the right was converted to 16-bit by setting Unity's importer to 4444 (TextureImporterFormat.ARGB16). Can you see the difference? On the right, the bright half shifts brighter and the dark half shifts darker. Can you see that the white part at the very left is wider in the right-hand image?

To make this error easier to see, I also prepared error images.

Error images

These are made by subtracting the compressed image from the original in a shader, so that the bigger the difference, the brighter it gets (available as a component called DiffImage). The left has similar error everywhere, but the right has large error, and so is bright, at both ends of the screen. The bright left end looks like what you'd get if, say, 0xf0 were rounded up to 0xff for an error of 15, and the dark right end like what you'd get if 0x0f were truncated to 0x00 for an error of 15. It seems that when Unity does the color reduction itself, it simply truncates.

The problem of how human vision works

Dropping to 16 levels looks stepped not just because there are few colors. It's also down to how human vision works. Our vision has a contrast-enhancing filter switched on at all times.

It's due to a mechanism called lateral inhibition, and it causes things like "a slightly darker color next to a bright color looks darker" and "a slightly brighter color next to a dark color looks brighter". The bands you see because of this are also called Mach bands.

A 4444 gradient enlarged

This is an enlarged image of a gradient converted to 4444. You can see five vertical bands, and inside each band it's basically the same color, but how does it look to you? Doesn't the left side of each band look darker and the right side brighter? That's your brain enhancing the contrast on its own, because of the neighboring bands. So if you hide the neighboring band, the effect goes away, and if you swap a dark band for a bright one, the enhancement goes the other way.

The same gradient with the bottom half flipped

I flipped the bottom half of the image left to right. To me, the color change within the bands feels smaller than in the previous image. Doesn't it look a little flat?

This contrast-enhancement effect seems to vary from person to person. The more strongly it works on someone, the more sensitive they may be to the degradation when the number of levels is reduced. Even if someone says "this doesn't bother me", it might bother someone else.

Dithering

To make the loss of image quality from reducing colors harder to notice, it helps to suppress this lateral inhibition. The effect of lateral inhibition is easy to see when large areas sit next to each other, but if you scatter the colors like noise, the emphasized lines get broken up and become hard to see.

On top of that, the resolution of human vision is limited, so if you look from a distance at a field where red and blue flowers are planted alternately, it looks purple. Scatter colors finely and, to take it to the extreme, you can make a picture that looks gray even with only black and white.

This "color-scattering process" is called dithering. This time I implemented the Floyd-Steinberg method, which has been around for a long time and is easy to implement. There's also an implementation for Unity that has been public for a long time, but this time I wanted one for 565 as well as 4444, and, as described above, I wanted to keep the error down at the very stage where the bits are cut, so I implemented it all together.

The results look like this.

Comparison of 565, 565 with dithering, 4444 and 4444 with dithering

Many people probably won't mind the difference between 565 and 565Dither. This time everything is drawn with point sampling, so you can see the difference if you zoom in, but normally it's drawn with bilinear sampling, which blurs the dithering dots, so it matters even less.

With 4444, on the other hand, there's quite a difference. Zoomed in, the dot pattern is plainly visible, but at 1:1 it's hard to see, and in practice a bilinear filter is applied, so it's even harder to see. If the illustrations are a selling point it probably isn't acceptable, but elsewhere it's surprisingly usable.

Let's look at a gradient too.

Gradients with dithering

The stripes in 4444 are much harder to see.

Implementing it in Unity

To implement this in Unity, you make a class that inherits from the AssetPostprocessor class and implement two methods, OnPreprocessTexture and OnPostprocessTexture.

If you just want Unity to reduce the colors, you can simply rewrite the importer setting to 4444 (ARGB16) or 565 (RGB16) in Preprocess and be done, but this time the process is "modify the texture data in memory after import", so we need PostProcess too.

Preprocess

First, on the Preprocess side, identify the source textures by some means (the path, in the sample), enable reading on the CPU, and set them to uncompressed.

importer.isReadable = true;
importer.textureCompression = TextureImporterCompression.Uncompressed;

Once this makes the original texture "readable" and "uncompressed", it can be processed in Postprocess.

Postprocess

Next, on the Postprocess side, apply color reduction and dithering to the texture data in memory once the import has finished, and then change the format to 4444 or 565.

Here's the main part of the processing.

for (int i = 0; i < texture.mipmapCount; i++)
{
    pixels = texture.GetPixels32(i);
    ColorReductionUtil.FloydSteinberg(pixels, func, width, height);
    texture.SetPixels32(pixels, i);
    width = Mathf.Max(1, width / 2); // to the next size
    height = Mathf.Max(1, height / 2); // to the next size
}
EditorUtility.CompressTexture(texture, format, quality: 100);

For every mip level, get the data with GetPixels32(), reduce the colors while dithering with FloydSteinberg(), write it to the texture with SetPixels32(), and finally change the format to 4444 or 565 with CompressTexture().

The result is saved under Library as the "imported texture" for each platform. The original file under Assets stays as it was before the color reduction and dithering.

Note that the color reduction (FloydSteinberg()) is done while still in 8888 (RGBA32). Each pixel's color is replaced with "the value after reducing it once and then filling in the digits to restore it". In other words, instead of turning 0xf0 into 0xe and writing that, it restores that further to 0xee before writing. Turning it into 0xe is done by Unity in EditorUtility.CompressTexture. Whether Unity properly minimizes the error or just truncates the bits, either way you end up with a correct image with small error.

The core implementation of color reduction and dithering

FloydSteinberg(), which does the actual color reduction and dithering, and the related implementation are in ColorReductionUtil.cs. The code isn't difficult, but if you're not used to bit operations, the reduction and restoration steps may be hard to follow. For example, reducing to 5 bits and restoring that to 8 bits looks like this.

var r = ((x.r * 62) + 255) / 510; //5bit
r = (r << 3) | (r >> 2);

The first line is the expression from earlier. After that, we generate 8 bits from these 5 bits. Call the 5 bits ABCDE. We fill in the top 3 bits, ABC, at the bottom to make ABCDEABC. We add the 5 bits shifted left by 3 bits (= multiplied by 8) to the 5 bits shifted right by 2 bits (= divided by 4) so that the top 3 bits come to the very bottom.

r = (r * 8) + (r / 4);

Writing it like this does the same thing.

Using it in a project

In this sample, color reduction and dithering are applied to images in folders with specific names.

Depending on the project, file names rather than folder names may be more convenient. Personally, I think "as long as it does the job, the less freedom the better", so I tried folders first. Tokyo Prison also controlled this by folder name.

As for setting the compression type, the importer for the sample (TestColorReductionImporter) lets you freely choose dithering on/off and 4444 or 565, but the importer meant more for production use (ColorReductionImporter) automatically chooses 4444 or 565 depending on whether there's an alpha channel, and always applies dithering. This too comes from the "as long as it does the job, the less freedom the better" principle.

What do you think?

Closing: wouldn't ETC2 do?

In Tokyo Prison, we used ETC1 or PVRTC for opaque images, but where there was translucency, effects in particular were almost all 4444. We also targeted OpenGLES2 machines, so ETC2 couldn't be used.

You could use a two-texture setup, with ETC1 or PVRTC for RGB and Alpha8 for alpha, but that needs dedicated components and shaders, and once you factor in atlases too, it's quite a hassle to manage. On top of that, the parts that use Spine are hard to touch. So we made the decision: "it only halves the size and it's ugly, but we'll put up with 4444".

Honestly, 4444 is ugly. Even with dithering the quality isn't good enough, and having only 16 levels in the alpha channel is quite a letdown too. Still, for hazy images like clouds and smoke, or effects that animate fast, it was within the acceptable range.

All the same, the conclusion is "wouldn't ETC2 do?" If you're only targeting OpenGLES3 and later, it's best to consider ETC2 first.

Next time, I'll bring you another article that concludes with "wouldn't ETC2 do?"

Bonus: RGB332

RGB332 with dithering

Getting carried away, I also made a picture with dithering in 3 bits of red, 3 bits of green and 2 bits of blue. That lets you fit RGB into Alpha8. To me it has a strangely nostalgic feel. Do the same to make 1-bit black and white, and you can fit 8 pixels into an Alpha8 pixel, so 1024x1024 fits into a mere 128KB. I hope someone finds an interesting use for it.