/*
   AA Shader v1.5
   
   Copyright (C) 2012 guest(r) - guest.r@gmail.com

   This program is free software; you can redistribute it and/or
   modify it under the terms of the GNU General Public License
   as published by the Free Software Foundation; either version 2
   of the License, or (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

*/

uniform sampler2D OGL2Texture;
uniform vec4 OGL2Param;

void main()
{
    vec3 c11 = texture2D(OGL2Texture, gl_TexCoord[0].xy).xyz;
    vec3 s00 = texture2D(OGL2Texture, gl_TexCoord[1].xy).xyz; 
    vec3 s20 = texture2D(OGL2Texture, gl_TexCoord[2].xy).xyz; 
    vec3 s22 = texture2D(OGL2Texture, gl_TexCoord[3].xy).xyz; 
    vec3 s02 = texture2D(OGL2Texture, gl_TexCoord[4].xy).xyz; 
    vec3 c00 = texture2D(OGL2Texture, gl_TexCoord[5].xy).xyz; 
    vec3 c22 = texture2D(OGL2Texture, gl_TexCoord[6].xy).xyz; 
    vec3 c20 = texture2D(OGL2Texture, gl_TexCoord[5].zw).xyz;
    vec3 c02 = texture2D(OGL2Texture, gl_TexCoord[6].zw).xyz;
    vec3 c10 = texture2D(OGL2Texture, gl_TexCoord[1].zw).xyz; 
    vec3 c21 = texture2D(OGL2Texture, gl_TexCoord[2].zw).xyz; 
    vec3 c12 = texture2D(OGL2Texture, gl_TexCoord[3].zw).xyz; 
    vec3 c01 = texture2D(OGL2Texture, gl_TexCoord[4].zw).xyz;     
    vec3 dt = vec3(1.0,1.0,1.0);

    float d1=dot(abs(c00-c22),dt)+0.001;
    float d2=dot(abs(c20-c02),dt)+0.001;
    float hl=dot(abs(c01-c21),dt)+0.001;
    float vl=dot(abs(c10-c12),dt)+0.001;
    float m1=dot(abs(s00-s22),dt)+0.001;
    float m2=dot(abs(s02-s20),dt)+0.001;

    c11 =.5*(m2*(s00+s22)+m1*(s02+s20))/(m1+m2);

    float k1=hl+vl;
    float k2=d1+d2;
    
    vec3 t1=(hl*(c10+c12)+vl*(c01+c21)+k1*c11)/(3.0*(hl+vl));
    vec3 t2=(d1*(c20+c02)+d2*(c00+c22)+k2*c11)/(3.0*(d1+d2));

    k1=dot(abs(t1-c11),dt)+0.001;
    k2=dot(abs(t2-c11),dt)+0.001;

    c11 = (k1*t2 + k2*t1)/(k1+k2);

    vec3 mn1 = min(min(c00,c01),c02);
    vec3 mn2 = min(min(c10,c11),c12);
    vec3 mn3 = min(min(c20,c21),c22);

    vec3 mx1 = max(max(c00,c01),c02);
    vec3 mx2 = max(max(c10,c11),c12);
    vec3 mx3 = max(max(c20,c21),c22);

    mn1 = min(min(mn1,mn2),mn3);
    mx1 = max(max(mx1,mx2),mx3);

    vec3 dif1 = abs(c11-mn1) + 0.01*dt; dif1*=dif1; k1=dot(dif1,dt);
    vec3 dif2 = abs(c11-mx1) + 0.01*dt; dif2*=dif2; k2=dot(dif2,dt);

    gl_FragColor.xyz=(k1*mx1+k2*mn1)/(k1+k2);
}