I'm writing a function that should count how many pixels of the same color are around a certain pixel, this is for WebGL. The width of the (rectangle) area w has a large effect on performance (as expected), so I'd like to ask if I there are any obvious ways to make this code work faster, thank you!
float neighCount(float id, sampler2D tex, vec2 vuv, vec2 uvpix, float w) {
float cnt = 0.0;
vec2 beg = vuv - vec2(0.5 * w * uvpix);
for(float r = 0.0; r < w; r++) {
float y = uvpix.y * r;
for(float c = 0.0; c < w; c++) {
float tid = texture2D(tex, beg + vec2(uvpix.x * c, y)).r;
if(abs(id - tid) < 0.05 || tid == 0.0) cnt += 1.0;
}
}
return smoothstep(0.0, 1.0, cnt / (w * w));
}