uniform sampler2D layer0;
uniform sampler2D layer0d;
uniform sampler2D layer1;
uniform sampler2D layer1d;

uniform float l1opacity;

uniform float membraneFill;
uniform float membraneSpec;

void main(){
  vec2 texCoord = gl_TexCoord[0].st;

  vec4 l0 = texture2D(layer0, texCoord);
  vec4 l0d = texture2D(layer0d, texCoord);
  vec4 l1 = texture2D(layer1, texCoord);
  vec4 l1d = texture2D(layer1d, texCoord);
  
  //gl_FragColor = l1; return;
     
  vec4 c0;
  vec4 c1;
  
  if (l0d.r >= l1d.r)
  {
    c0 = l0;
    c1 = l1;    
  }
  else
  {
    c0 = l1;
    c1 = l0;
  }
  
  //vec4 c_ = vec4(c0.rgb + c1.rgb * (1 - c0.a), c0.a + c1.a * (1.0 - c0.a));
  //c_ = vec4(c_.rgb + c2.rgb * (1 - c_.a), c_.a + c2.a * (1.0 - c_.a));
  
  /*vec4 c_ = vec4(c1.rgb * c1.a + c0.rgb * (1.0 - c1.a), clamp(c0.a + c1.a, 0.0, 1.0));
       c_ = vec4(c2.rgb * c2.a + c_.rgb * (1.0 - c2.a), clamp(c_.a + c2.a, 0.0, 1.0));*/
       
  vec4 c_ = l0;  
  
  vec3 gray = vec3(0.5,0.6,1);
  l1.a *= membraneFill;
       c_ = vec4(gray * l1.a + c_.rgb * (1.0 - l1.a), clamp(c_.a + l1.a, 0.0, 1.0));

  vec3 white = vec3(1,1,1);
  //l1.b = pow(l1.b, 1.0);
  l1.b = clamp(l1.b, 0.0, 1.0);
  l1.b = l1.b / (membraneSpec * (1 - l1.b) + 1.0);
  
       c_ = vec4(white * l1.b + c_.rgb * (1.0 - l1.b), clamp(c_.a + l1.b, 0.0, 1.0));

  vec3 black = vec3(0);
  l1.r = 1.0 - l1.r;
       c_ = vec4(black * l1.r + c_.rgb * (1.0 - l1.r), clamp(c_.a + l1.r, 0.0, 1.0));

  //gl_FragColor = vec4(vec3(c_.rgb), 1.0);  
    
  //float depth = min(l0d.r, min(l1d.r, min(l2d.r, l3d.r)));

  
  
  float depth = min(1.0, max(0.0, min(l0d.r, l1d.r)));
  gl_FragColor = vec4(vec3(mix(l0.rgb, c_.rgb, l1opacity)), 1.0);
  
  //gl_FragColor = l3;
 
  gl_FragDepth = depth;
  gl_FragDepth = 1.0; 
  
  //gl_FragColor=vec4(1.0, 0.0, 1.0, 1.0);

}
