Hi,

I’m trying to read some texture value in my shader, but I need an algorithm to make it more efficient:
I want to read the pixel color from the first x where the mask isn’t null.
Something like this :

My issue is that for each pixel, I don’t want to have to go read the texture X times to find the color pixel of my mask. - X being the difference between the current pixel and the first non null pixel of my mask - .

This is what I’m trying to do reasonnable step size of 5%, but it doesn’t want to compute because of the recursion -apparently -.

``````// ==============================================
vec2 glitchCoords(sampler2D _tex, vec2 uv){

float alpha = texture2D( _tex, uv).r;
if(alpha == 0.0){
if(uv.x + 0.05 < 1.0){
uv = glitchCoords(_tex, vec2(uv.x + 0.05, uv.y) );
}
}else{

}

return uv;
}
``````

Any pointers to how i could do this?

I’m sure I’m missing somehing obvious…

Thanbks

In this case you can replace the recursion with a loop, e.g.

``````float alpha;
for (; uv.x < 1.0; uv.x += 0.05) {
alpha = texture2D( _tex, uv).r;
if (alpha > 0.0)
return uv;
}
``````

But bear in mind that GPUs get most of their advantages from parallelism and are less efficient when dealing with non-uniform control flow.

If the mask is static, it would be better to pre-process the mask and store the X coordinate of the next non-transparent pixel. If the mask is dynamic, an efficient technique would be a divide-and-conquer algorithm similar to a parallel prefix sum.

1 Like