import glitch, glitch.glut
import glitch.PIL.image as image

import OpenGL.GL.shaders as shaders

class HorizontalBlur(glitch.Shader):
    vertex = """
        void main()
        {
            gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;
            gl_TexCoord[0] = gl_MultiTexCoord0;
        }
        """

    fragment = """
        uniform sampler2D tex;
        uniform int width;
        uniform int height;

        void main ()
        {
            float tx = gl_TexCoord[0].x;
            float ty = gl_TexCoord[0].y;

            float step = 1.0 / float(width);
            gl_FragColor =
                0.05 * texture2D(tex, vec2(tx - 4.0 * step, ty)) +
                0.09 * texture2D(tex, vec2(tx - 3.0 * step, ty)) +
                0.12 * texture2D(tex, vec2(tx - 2.0 * step, ty)) +
                0.15 * texture2D(tex, vec2(tx - 1.0 * step, ty)) +
                0.16 * texture2D(tex, vec2(tx - 0.0 * step, ty)) +
                0.15 * texture2D(tex, vec2(tx + 1.0 * step, ty)) +
                0.12 * texture2D(tex, vec2(tx + 2.0 * step, ty)) +
                0.09 * texture2D(tex, vec2(tx + 3.0 * step, ty)) +
                0.05 * texture2D(tex, vec2(tx + 4.0 * step, ty));
        }
        """

    def set_uniforms(self, ctx, shader):
        # XXX: Assumes texture unit 0.
        loc = shaders.glGetUniformLocation(shader, 'tex')
        shaders.glUniform1i(loc, 0)

        (w, h) = ctx['texture_size']
        loc = shaders.glGetUniformLocation(shader, 'width')
        shaders.glUniform1i(loc, w)
        loc = shaders.glGetUniformLocation(shader, 'height')
        shaders.glUniform1i(loc, h)

if __name__ == '__main__':
    import sys

    texture = image.ImageTexture.from_file(sys.argv[1])
    camera = glitch.glut.GLUTCamera(eye=[0, 0, 1], children=[
        glitch.Translate(-0.5, -0.5, children=[
            glitch.ApplyTexture(texture, children=[
                HorizontalBlur(children=[
                    glitch.TexturedRectangle()])])])])
    camera.run()
