Saturday, September 25, 2010

GLSL: Integer Array

For the last few months I've been dealing with GLSL. Come to my surprise there are many things GLSL capable of doing, but not documented properly over the internet. And the how-to solution is pretty much easy. Not like it contain some kind of hardcore logic stuff, just a few syntax that, if properly put, is easy to do. These are some to name a few:

1. Array in GLSL
One of my obstacle in my thesis is to build a massive single index array and send it to GPU. However, there are limit of variables you can send to GPU. If you want to send a massive array, you have to send it as a texture. So the first thing came up in my mind is a single index texture or GL_TEXTURE_1D. Now at first it might seems to work but the problem is the limit of item you can put as a single 1 dimension texture is very limited. I cant say the exact number, but words on the internet is it was limited up to 80,000 texel. Dont mix it up with GPU Memory capability though. You can put lots of 1D texture as far as your GPU memory can do, just dont put a texture with more than 80,000 index(texel). This also happens with 2D texture. I cant put something beyond 2000 x 2000. Since my program require more than that, I am obligated to put a 3D texture to simulate my array. Off course you will have to do a more complicated indexing when accessing it on GPU.

2. Integer Texture
There might be time you want to put a 32 bit Integer to your texture. For some reason, this kind of thing are really hard to find over the internet. So how to do this is basically the same as if you want to put a normal texture, but you want to change your internal format to GL_R32I and your format to GL_RED_INTEGER when transferring the texture to GPU memory. So for example my syntax would be:

glTexImage3D(GL_TEXTURE_3D, GL_R32I, width, height, depth, 0, GL_RED_INTEGER, GL_INT, index);

Inside the fragment shader, at the very top of the code, include this header

#extension GL_EXT_gpu_shader4 : require
#extension GL_EXT_geometry_shader4 : require
#extension GL_EXT_texture_integer : require

to enable some extension so you can use integer based texture. When defining your texture you use isampler instead of sampler, eg:

uniform isampler3D texIndex;

to create an integer 3d texture.

3. Integer index accessing
Off course the key of an array is to access the item using integer value. To do this, you can use texelFetch command, eg:

texelFetch(texIndex, ivec, 0);

texIndex is your texture. ivec is an integer vector, it can be ivec2 or ivec3, based on the texture type you use (texture 2D or 3D). The last item is sampling. Im not sure how it works but I think it sampling the neighbor of the selected pixel. 

There you go, now you can send any huge integer to the GLSL and treat it as if it was an array. Feel free to comment if you have any question regarding this.

1 comment:

Anonymous said...

your blog has been read :-)