// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.  
// 灰化特效
// 原理：
// r = 0.2126 * r + 0.7152 * g + 0.0722 * b
// g = 0.2126 * r + 0.7152 * g + 0.0722 * b
// b = 0.2126 * r + 0.7152 * g + 0.0722 * b

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


CCProgram unlit-vs %{
  precision highp float;

  #include <builtin/uniforms/cc-global>
  #include <builtin/uniforms/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 unlit-fs %{
  precision highp float;
  
  #include <builtin/internal/alpha-test>

  in vec4 v_color;

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

  #if USE_GRAY
  uniform GrayPhoto {
    // 灰化程度
    float grayLevel;
  };
  #endif

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

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

    o *= v_color;

    ALPHA_TEST(o);

    #if USE_GRAY
    vec4 srcColor = o;

    float gray = 0.2126 * o.r + 0.7152 * o.g + 0.0722 * o.b;
    vec4 grayColor = vec4(gray, gray, gray, o.a);

    o = srcColor + (grayColor - srcColor) * grayLevel;
    #endif
    gl_FragColor = o;
  }
}%
