Screen space outline with Color Rect

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Niko

I’m using a Viewport Container for outlining groups of Sprites and Polygons2D, each group has its own outline color and this is becoming quite inefficient, using a Color Rect shader would be the way to go but normal outline shaders don’t work as pixel alpha is always 1.0 on the screen, I’m using GDquest outline shader:

shader_type canvas_item;

uniform vec4 line_color : hint_color = vec4(1);
uniform float line_thickness : hint_range(0, 10) = 1.0;

const vec2 OFFSETS[8] = {
	vec2(-1, -1), vec2(-1, 0), vec2(-1, 1), vec2(0, -1), vec2(0, 1), 
	vec2(1, -1), vec2(1, 0), vec2(1, 1)
};

void fragment() {
	vec2 size = TEXTURE_PIXEL_SIZE * line_thickness / 2.0;
	vec4 color = texture(TEXTURE, UV);
	
	float inline = 1.0;
	float outline = 0.0;
	for (int i = 0; i < OFFSETS.length(); i++) {
		float sample = texture(TEXTURE, UV + size * OFFSETS[i]).a;
		outline += sample;
		inline *= sample;
	}
	outline = min(1.0, outline) - color.a;
	inline = (1.0 - inline) * color.a;
	
	vec4 outlined_result = mix(color, line_color, outline + inline);
	COLOR = mix(color, outlined_result, outlined_result.a);
}