Get the right color encoding for texture in shader

I have my texture with RGB encoding:

texture.encoding = THREE.sRGBEncoding

The same for the render output:

renderer.outputEncoding = THREE.sRGBEncoding

It works for the MeshStandardMaterial:

When I replace MeshStandardMaterial for ShaderMaterial and provide the texture as uniform to shader the color get wrong again:

How can I set the right color encoding for the shader approach?

You probably do not decode the sRGB encoded color values to linear color space. Use this code in your custom shader:

2 Likes

Thank you for the answer. I spent some time trying to implement that, but I’m shooting in the dark. I tried to include the shader chunk this way:

//fragment.glsl

#include <encodings_pars_fragment>;

uniform sampler2D uTexture;
varying vec2 vUv;

void main()
{
    vec4 textureColor = texture2D(uTexture, vUv);

    vec4 textureColor = sRGBToLinear(textureColor);

    gl_FragColor = textureColor;
}

And I’m getting this error:

Captura de pantalla 2021-12-02 a las 16.13.45

I have a fix. For the shader material approach just I have to remove:

texture.encoding = THREE.sRGBEncoding

And the color is fixed. Anyway, any thought about how to use the peviously mentioned ShaderChunk are welcome.

The error messages say that encodings_pars_fragment is already included.

1 Like

Ok, thanks!

So, this works:

uniform sampler2D uTexture;
varying vec2 vUv;
void main()
{
    vec4 textureColor = texture2D(uTexture, vUv);
    textureColor = sRGBToLinear(textureColor);
    gl_FragColor = textureColor;
}

Looks good. I suggest you use this approach instead of not setting the encoding property to THREE.sRGBEncoding. With the above code, you have a correct color space workflow.

1 Like