GLSL point inside box test

Use step function to avoid branching and get the best performance:

// return 1 if v inside the box, return 0 otherwise
float insideBox(vec2 v, vec2 bottomLeft, vec2 topRight) {
    vec2 s = step(bottomLeft, v) - step(topRight, v);
    return s.x * s.y;   
}

float insideBox3D(vec3 v, vec3 bottomLeft, vec3 topRight) {
    vec3 s = step(bottomLeft, v) - step(topRight, v);
    return s.x * s.y * s.z; 
}

void main() {
    vec4 texel = texture2D(texUnit, texCoord);

    float t = insideBox(v_position, vec2(0, 0), vec2(1, 1));
    gl_FragColor = t * texel + (1 - t) * color;
}

Based on damphat's answer, I've implemented a function for a smooth transition between inside and outside the rectangle:

float inside_rectangle_smooth(vec2 p, vec2 bottom_left, vec2 top_right, float transition_area)
{
    vec2 s = smoothstep(bottom_left, bottom_left + vec2(transition_area), p) -
             smoothstep(top_right - vec2(transition_area), top_right, p);
    return(s.x * s.y);
}

Use the "transition_area" parameter to tune the size of the transition area between inside and outside the rectangle. The transition is faded inside the rectangle, not outside of it. Also make sure the "transition_area" parameter is smaller than the distance between "bottom_left" and "top_right" (in each dimension).
I'm successfully using this function to fade shadows in my engine (using shadow map coordinates).

Demonstration:
inside_rectangle_smooth(v_texture_coordinate, vec2(0.0), vec2(1.0), 0.1)
The above image is produced by calling:
inside_rectangle_smooth(v_texture_coordinate, vec2(0.0), vec2(1.0), 0.1)


I just cam across this solution. Via https://github.com/stackgl/shader-school

bool inBox(highp vec2 lo, highp vec2 hi, highp vec2 p) {
    bvec4 b = bvec4(greaterThan(p, lo), lessThan(p, hi));
    return all(b);
}

Tags:

Opengl

Glsl