Smooth outline 2D

A shader for outline, with smoothness to fade out edges. Also an option for having the shader pulse over time.

 

Updated for Godot 3.5

Shader code
shader_type canvas_item;
render_mode unshaded;

uniform bool Smooth = true;
uniform float width : hint_range(0.0, 64) = 1.0;
uniform vec4 outline_color : hint_color = vec4(0.0, 0.0, 0.0, 1.0);
uniform int pixel_size : hint_range(1, 10) = 4;
uniform float width_speed :hint_range(0.1, 10) = 1;

void fragment()
{
    float _width = width + ((sin(TIME*width_speed) + 1.0) -2.0) * 10.0;
    vec2 unit = (1.0/float(pixel_size) ) / vec2(textureSize(TEXTURE, 0));
    vec4 pixel_color = texture(TEXTURE, UV);
    if (pixel_color.a == 0.0) {
        pixel_color = outline_color;
        pixel_color.a = 0.0;
        for (float x = -ceil(_width); x <= ceil(_width); x++) {
            for (float y = -ceil(_width); y <= ceil(_width); y++) {
                if (texture(TEXTURE, UV + vec2(x*unit.x, y*unit.y)).a == 0.0 || (x==0.0 && y==0.0)) {
                    continue;
                }
                if (Smooth) {
                    pixel_color.a += outline_color.a / (pow(x,2)+pow(y,2)) * (1.0-pow(2.0, -_width));
                    if (pixel_color.a > 1.0) {
                        pixel_color.a = 1.0;
                    }
                } else {
                    pixel_color.a = outline_color.a;
                }
            }
        }
    }
    COLOR = pixel_color;
}
The shader code and all code snippets in this post are under CC0 license and can be used freely without the author's permission. Images and videos, and assets depicted in those, do not fall under this license. For more info, see our License terms.

More from Tanders

Wiggle 2D

Related shaders

Smooth outline 2D with enable disable system

Smooth Color Gradient

Smooth Radial Gradient

Subscribe
Notify of
guest

4 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
zkmark
zkmark
2 years ago

The line is not drawn on the outside edges of the image.
Can you add a margin? For example this one has the option to add margin
https://godotshaders.com/shader/2d-outline-inline/

adictonator
adictonator
2 years ago

this is not working at all in Godot 3.5

endritDev-YellowHatGames
Reply to  adictonator

If it’s not working (Godot 3.5) you need to correct a few stuff.
Line 12 all the f values need to be fallowed by a .0 (1.0f).
Remove “return” on line 30

Master35
Master35
2 years ago

thanks

Last edited 2 years ago by Master35