I am trying to render a rectangle in OpenGL with one rounded corner, as such:
I have a shader that successfully accomplishes this on Shadertoy, shown below:
const vec4 color = vec4(1);
const vec2 half_size = vec2(150.0, 100.0);
const float radius = 20.0;
// from https://iquilezles.org/articles/distfunctions
float roundedBoxSDF(vec2 center, vec2 size, float radius) {
radius = (center.x < 0.0 && center.y > 0.0) ? radius : 0.0;
vec2 q = abs(center) - size + radius;
return min(max(q.x,q.y),0.0) + length(max(q,0.0)) - radius;
}
void mainImage( out vec4 fragColor, in vec2 fragCoord ) {
vec2 center = (fragCoord - iResolution.xy / 2.0);
float distance = roundedBoxSDF(center, half_size, radius);
float smoothedAlpha = 1.0 - smoothstep(-1.0, 1.0, distance);
fragColor = mix(vec4(0), color, smoothedAlpha);
}
Unfortunately, I am running into a problem that occurs when the radius of the rounded corner becomes larger than half of the rectangle's width or height, where it becomes clipped:
I understand that this is due to the radius being set based upon the pixel's location in the roundedBoxSDF()
function. Is there a better way to accomplish this type of shape, while avoiding the problems of the corner radius being cut off at certain sizes?
Also, would this be better done by first rendering the rectangle texture, and then just applying a stencil?