package org.helioviewer.filter.runningdifference;

import javax.media.opengl.GL;

import org.helioviewer.viewmodel.view.opengl.shader.GLFragmentShaderProgram;
import org.helioviewer.viewmodel.view.opengl.shader.GLShaderBuilder;
import org.helioviewer.viewmodel.view.opengl.shader.GLShaderBuilder.GLBuildShaderException;
import org.helioviewer.viewmodel.view.opengl.shader.GLTextureCoordinate;

public class DifferenceShader extends GLFragmentShaderProgram {
    private GLTextureCoordinate isDifference;
    private GLTextureCoordinate differenceAngle;

    private static int ID = 0;
    int mode = -1;

    public void setIsDifference(GL gl, float isDifference) {
        this.isDifference.setValue(gl, isDifference);
    }

    public void setDifferenceAngle(GL gl, float differenceAngle) {
        this.differenceAngle.setValue(gl, differenceAngle);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void buildImpl(GLShaderBuilder shaderBuilder) {

        try {
            isDifference = shaderBuilder.addTexCoordParameter(1);
            differenceAngle = shaderBuilder.addTexCoordParameter(1);
            shaderBuilder.getParameterList().add("float4 " + "texcoord4" + " : TEXCOORD4");
            String program = "";
            program = "if(isdifference>0.5){\toutput.r = ( output.r - tex2D(differenceImage, texcoord4.xy).r)/(output.r);";
            program += "\tvec4 tr = vec4(0.05f,0.05f,0.05f,0.05f);";
            program += "output.r = (output.r + 1.0f)/2.0f;}";
            // program =
            // "\toutput.rgb = tex2D(differenceImage, texcoord0.xy).rgb;";

            program = program.replaceAll("output", shaderBuilder.useOutputValue("float4", "COLOR"));

            mode = shaderBuilder.addTextureParameter("sampler2D differenceImage");
            ID = (ID + 1) & 15;
            program = program.replace("isdifference", isDifference.getIdentifier(1));
            program = program.replace("differenceAngle", differenceAngle.getIdentifier(1));

            shaderBuilder.addMainFragment(program);
            System.out.println("SHADERDIFF: " + shaderBuilder.getCode());
        } catch (GLBuildShaderException e) {
            e.printStackTrace();
        }
    }

    public void activateDifferenceTexture(GL gl) {
    }
}

@@ -1298,18 +1298,16 @@
 tput.r =
- (
  output.
@@ -1352,20 +1352,8 @@
 y).r
-)/(output.r)
 ;%22;%0A
@@ -1382,47 +1382,24 @@
  %22%5Ct
-vec4
+float
  tr = 
-vec4(0.05f,0.05f,0.05f,0.05f)
+0.05f
 ;%22;%0A
@@ -1420,18 +1420,19 @@
 ogram +=
- 
 %22
+%5Ct
 output.r
@@ -1434,16 +1434,21 @@
 put.r = 
+clamp
 (output.
@@ -1452,23 +1452,20 @@
 ut.r
- + 1.0f)/2.0f;%7D
+,-tr,tr)/tr;
 %22;%0A 
@@ -1474,19 +1474,16 @@
         
- //
  program
@@ -1487,25 +1487,10 @@
 ram 
++
 =
-%0A            // 
 %22%5Cto
@@ -1500,54 +1500,62 @@
 ut.r
-gb
  = 
-tex2D(differenceImage, texcoord0.xy).rgb;
+(output.r + 1.0f)/2.0f;%22;%0A            program += %22%7D
 %22;%0A%0A

Set clamping