Tuesday, May 3, 2011

Bitwise Operators on Low End GPU's

hi
recently i was needed to perform bitwise operators on SM 3, but as you know, SM 3- doesn't support it (only DX10 SM 4.0 and up).
if you try to write this line: (hlsl SM 3 for example):
some_var & 2
you will get error message saying: Bitwise operations not supported on legacy targets.
the technique i present here can be used for few more things (lighting, shading etc), but here i will show how to do bitwise ops with it.
i support: &, |, ^ (AND,OR,XOR) - more complicated operators could be used but these are the base.
the trick is to use a texture to store the results of these operators, and then to sample this texture and get the result.
a code to compute this texture will look like this: (assuming 8 bit range for AND op)
for i=0 to 255
for j=0 to 255
texture[i][j] = i & j
to maximize storage, encode different operators on different channels.
here is a sample texture that encode AND,OR,XOR in different channels:

bitwise operators texture: AND,OR,XOR

the way you use this texture in your shader looks something like this: (hlsl style)
float AND(in float A, in float B)
{
tex2Dlod(BitwiseOpMap, float4(A, B,0,0)).r;
}

NOTE: make sure you use POINT sampling, you don't want to filter the results in the texture, you also don't need mipmaps...

thats it, i hope you find this post useful...
cya until next time ;)

2 comments:

Chris said...

<3

orenk2k said...

hi

i guess you meant shader model < 3, you are right! but it better to write what you meant than let me guess what is <3 don't you think? :)

cya