import gh_renderer  
import gh_gpu_program


def gpu_program_create(gpu_prog_name, vs_gl2, ps_gl2, vs_gl3, ps_gl3, vs_gles2, ps_gles2):
  vs = ""
  ps = ""
  if (gh_renderer.is_opengl_es() == 1):
    vs = vs_gles2
    ps = ps_gles2
  
  else:
    if (gh_renderer.get_api_version_major() > 3):
      vs = "#version 150\n" + vs_gl3
      ps = "#version 150\n" + ps_gl3
    
    elif (gh_renderer.get_api_version_major() == 3):
      if (gh_renderer.get_api_version_minor() < 2):
        vs = "#version 130\n" + vs_gl3
        ps = "#version 130\n" + ps_gl3
      else:
        vs = "#version 150\n" + vs_gl3
        ps = "#version 150\n" + ps_gl3

    elif (gh_renderer.get_api_version_major() < 3):
      vs = vs_gl2
      ps = ps_gl2
  
  p = gh_gpu_program.create_v2(gpu_prog_name, vs, ps)
  return p





def init_texture_shader():

  vs_gl3=""" 
  in vec4 gxl3d_Position;
  in vec4 gxl3d_TexCoord0;
  out vec4 v_uv;
  uniform mat4 gxl3d_ModelViewProjectionMatrix; // Automatically passed by GeeXLab
  uniform vec4 uv_tiling;
  void main()
  { 
    vec4 P = gxl3d_Position;
    P.w = 1.0;
    gl_Position = gxl3d_ModelViewProjectionMatrix * P;
    v_uv = gxl3d_TexCoord0 * uv_tiling;
  }
  """


  ps_gl3="""
  uniform sampler2D tex0;
  in vec4 v_uv;
  out vec4 FragColor;
  void main()
  {
    vec2 uv = v_uv.xy;
    //uv.y *= -1.0;
    FragColor = texture(tex0, uv);
  }
  """


  vs_gl2="""
  #version 120 
  varying vec4 v_uv; 
  uniform mat4 gxl3d_ModelViewProjectionMatrix; // Automatically passed by GeeXLab 
  uniform vec4 uv_tiling; 
  void main() 
  { 
    vec4 P = gl_Vertex; 
    P.w = 1.0; 
    gl_Position = gxl3d_ModelViewProjectionMatrix * P; 
    v_uv = gl_MultiTexCoord0 * uv_tiling; 
  }
  """

  ps_gl2="""
  #version 120 
  uniform sampler2D tex0; 
  varying vec4 v_uv; 
  void main() 
  { 
    vec2 uv = v_uv.xy;
    uv.y *= -1.0;
    gl_FragColor = texture2D(tex0, uv);
  }
  """


  vs_gles2="""
  precision highp float;
  attribute vec4 gxl3d_Position;
  attribute vec4 gxl3d_TexCoord0;
  varying vec4 v_uv; 
  uniform mat4 gxl3d_ModelViewProjectionMatrix; // Automatically passed by GeeXLab
  uniform vec4 uv_tiling;
  void main()
  { 
    vec4 P = gxl3d_Position;
    P.w = 1.0;
    gl_Position = gxl3d_ModelViewProjectionMatrix * P;
    v_uv = gxl3d_TexCoord0 * uv_tiling;
  }
  """

  ps_gles2="""
  precision highp float;
  uniform sampler2D tex0;
  varying vec4 v_uv; 
  void main()
  {
    vec2 uv = v_uv.xy;
    uv.y *= -1.0;
    gl_FragColor = texture2D(tex0, uv);
  }
  """

  prog = gpu_program_create("texture_prog", vs_gl2, ps_gl2, vs_gl3, ps_gl3, vs_gles2, ps_gles2)
  gh_gpu_program.uniform1i(prog, "tex0", 0)
  return prog

