// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.  
// 老照片特效
// 原理：
// r = 0.393 * r + 0.769 * g + 0.189 * b; 
// g = 0.349 * r + 0.686 * g + 0.168 * b; 
// b = 0.272 * r + 0.534 * g + 0.131 * b;

CCEffect %{
  techniques:
  - passes:
    - vert: vs
      frag: fs
      blendState:
        targets:
        - blend: true
      rasterizerState:
        cullMode: none
      properties:
        texture: { value: white }
        alphaThreshold: { value: 0.5 }
        # 老化程度
        oldLevel: {
          value: 1.0,
          inspector: {
            tooltip: "老化程度",
            range: [0.0, 1.0]
          }
        }
}%


CCProgram vs %{
  precision highp float;

  #include <cc-global>
  #include <cc-local>

  in vec3 a_position;
  in vec4 a_color;
  out vec4 v_color;

  #if USE_TEXTURE
  in vec2 a_uv0;
  out vec2 v_uv0;
  #endif

  void main () {
    vec4 pos = vec4(a_position, 1);

    #if CC_USE_MODEL
    pos = cc_matViewProj * cc_matWorld * pos;
    #else
    pos = cc_matViewProj * pos;
    #endif

    #if USE_TEXTURE
    v_uv0 = a_uv0;
    #endif

    v_color = a_color;

    gl_Position = pos;
  }
}%


CCProgram fs %{
  precision highp float;
  
  #include <alpha-test>

  in vec4 v_color;

  #if USE_TEXTURE
  in vec2 v_uv0;
  uniform sampler2D texture;
  #endif

  #if USE_OLD_PHOTO
  uniform OldPhoto {
    // 老化程度
    float oldLevel;
  }

  /**
   * 获取老化颜色
   * 
   * @param color 原始颜色 
   *
   * @return 老化后的颜色
   */
  vec4 getOldPhotoColor(vec4 color) {
    float r = 0.393 * color.r + 0.769 * color.g + 0.189 * color.b; 
    float g = 0.349 * color.r + 0.686 * color.g + 0.168 * color.b; 
    float b = 0.272 * color.r + 0.534 * color.g + 0.131 * color.b;
    return vec4(r, g, b, color.a);
  }
  #endif

  void main () {
    vec4 o = vec4(1, 1, 1, 1);

    #if USE_TEXTURE
    o *= texture(texture, v_uv0);
      #if CC_USE_ALPHA_ATLAS_TEXTURE
      o.a *= texture2D(texture, v_uv0 + vec2(0, 0.5)).r;
      #endif
    #endif

    o *= v_color;

    ALPHA_TEST(o);

    #if USE_OLD_PHOTO
    vec4 srcColor = o;
    vec4 oldColor = getOldPhotoColor(srcColor);

    o = srcColor + (oldColor - srcColor) * oldLevel;
    #endif
    gl_FragColor = o;
  }
}%
