Cool Transparency Formula

While I was thinking through a way to implement transparency in my graphics engine, I thought up a cool and fast way to render pixels at 50% transparency:

BASIC:
col0 = col0 SHR 1
col1 = col1 SHR 1
col0 = (col0 AND &h007F7F7F)
col1 = (col1 AND &h007F7F7F)
newcol = col0 + col1

C:
col0 >>= 1;
col1 >>= 1;
col0 = col0 & 0x007F7F7F;
col1 = col1 & 0x007F7F7F;
newcol = col0 + col1;

ASM:
mov eax, [col1]
mov ebx, [col2]
shr eax, 1
shr ebx, 1
and eax, 0x007F7F7F
and ebx, 0x007F7F7F
add eax, ebx
mov [newcol], eax


All these examples do is take the average of the two RGB values by using bit shifts and bit logic. Instead of adding by two and then dividing, it divides by two (shift right one) and adds them together. But before it adds the values together, it chops off the bits that may have bled over into the other bytes using the AND operator.

0x7F7F7F is 011111110111111101111111 in binary.

No comments:

Post a Comment