# Texture Blending in GLSL

I was recently faced with the simple problem of blending two textures in a GLSL shader and found no straightforward discussions of the topic, so I’ll try to collect my thoughts here. It’s a simple problem to be sure, but initially the solution was not obvious. The problem can be distilled or reframed as “Given two RGBA pixel values, generate a third that is a composite of the two.” There are of course many possible ways to combine two pixel values, but what I was after was a typical or conventional result, like blending layers in Photoshop with defaults. Wikipedia, as ever, has a full discourse on the subject of alpha blending which provided the key insight in the form of this equation. Why it took me so long, I don’t know, but it finally clicked that this formula represents the default OpenGL alpha blending function `glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)`

. Armed with that knowledge, the solution was trivial to implement:

```
uniform sampler2D tex0;
uniform sampler2D tex1;
void main()
{
vec4 t0 = texture2D(tex0, gl_TexCoord[0].st);
vec4 t1 = texture2D(tex1, gl_TexCoord[0].st);
gl_FragColor = (1.0 - t1.a) * t0 + t1.a * t1;
}
```

Update: Better still would be to use the built-in function mix:

```
uniform sampler2D tex0;
uniform sampler2D tex1;
void main()
{
vec4 t0 = texture2D(tex0, gl_TexCoord[0].st);
vec4 t1 = texture2D(tex1, gl_TexCoord[0].st);
gl_FragColor = mix(t0, t1, t1.a);
}
```