Random beginner-question #17: How to keep white and black in color-modulated sprite

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

Hi everyone,

I have a greyscale sprite-png with a range of shades from black to white. Modulating the visibility to different color-hues affects all shades including complete white and black, the same with the different material/canvas item blend-modes.

What I would like to achieve is that 100% white and black stay untouched while colorising the grey-shades. Is that possible?

:bust_in_silhouette: Reply From: p7f

Hi! you have to write a shader for that.

modulate just multiplies the texture color with the modulate color, so if you want the same effect, but avoiding touching black and white colors, you could add this shader to the sprite:

shader_type canvas_item;
uniform vec4 modulate : hint_color = vec4(1.0);

void fragment(){
	vec4 color = texture(TEXTURE,UV);

	if (color.a == 1.0){
    if (color.rgb != vec3(1.0) && color.rgb != vec3(0.0)){
        	color *= modulate;
	COLOR = color;

Instead of changing the modulate property of the sprite, change the modulate param in the shader params from the editor.

Brilliant, thanks a million!

pferft | 2020-09-10 12:34

I’m sure there is a way to “smoothen the gradients”… ignoring pure black and white leads to sharp edges here, looking “1-Bit-y”, so I wonder how to “feather” those edges. Is it possible to expand the range from pure white to, say, including the “10% brightest greys” (and the darkest according to black), to achieve something like the “add” blend mode in an canvas material?

pferft | 2020-09-14 11:41

Hi! Sorry, but i dont quite understand what you are asking. Would you share an image or something of what you want to achieve. The add blend mode sums the texture color with the background color. Is that what you need?
Also, maybe opening a second question for this is a good idea… so others can see it and help too.

p7f | 2020-09-14 11:48

Yes, sorry I obviously got carried away a bit with my thoughts and you’re right, I probably should put this into an extra question. Thanks again for your code, it does what I asked for quite wonderfully!

For completion, this is what I meant:
(Oh, it seems I can’t put a picture in here… so here’s a link:)
WeTransfer - Send Large Files & Share Photos Online - Up to 2GB Free
The white areas in the shader-version are kind of “hard”. For the “want”-version I layered a colored layer on top of the original in add-mode…

pferft | 2020-09-14 17:15