/** 卡通效果 */

CCEffect %{
  techniques:
  - passes:
    - vert: sprite-vs:vert
      frag: sprite-fs:frag
      depthStencilState:
        depthTest: false
        depthWrite: false
      blendState:
        targets:
        - blend: true
          blendSrc: src_alpha
          blendDst: one_minus_src_alpha
          blendDstAlpha: one_minus_src_alpha
      rasterizerState:
        cullMode: none
      properties:
        highLightTexture: { value: white }
        u_normalMap: { value: white }
        alphaThreshold: { value: 0.5 }
}%

CCProgram sprite-vs %{
  precision highp float;
  #include <cc-global>
  #if USE_LOCAL
    #include <cc-local>
  #endif

  in vec3 a_position;
  in vec2 a_texCoord;
  in vec4 a_color;

  out vec4 v_color;
  out vec2 v_uv0;

  #if USE_TEXTURE
    in vec2 a_uv0;
  #endif

  vec4 vert () {
    vec4 pos = vec4(a_position, 1);

    #if USE_LOCAL
      pos = cc_matWorld * pos;
    #endif

    #if USE_PIXEL_ALIGNMENT
      pos = cc_matView * pos;
      pos.xyz = floor(pos.xyz);
      pos = cc_matProj * pos;
    #else
      pos = cc_matViewProj * pos;
    #endif

    #if USE_TEXTURE
      v_uv0 = a_uv0;
    #endif

    v_color = a_color;
    v_uv0 = a_texCoord;

    return pos;
  }
}%


CCProgram sprite-fs %{
  precision highp float;
  #include <embedded-alpha>
  #include <alpha-test>
  #include <cc-global>
  
  in vec4 v_color;

  #if USE_TEXTURE
    in vec2 v_uv0;
    #pragma builtin(local)
    layout(set = 2, binding = 10) uniform sampler2D cc_spriteTexture;
  #endif

  uniform sampler2D highLightTexture;
  uniform sampler2D u_normalMap;

  vec3 waveNormal(vec2 p) { 
    // 避免法线图边缘穿帮
    // fract返回小数部分 mod取模
    // 0.1 0.2 ... 0.9 1.0 0.9 ... 0.1 0.0 0.1 0.2 ...
    float x = mod(p.x , 2.0) < 1.0 ? fract(p.x) : 1.0 - fract(p.x);
    float y = mod(p.y , 2.0) < 1.0 ? fract(p.y) : 1.0 - fract(p.y);
    vec3 normal = texture(u_normalMap, vec2(x , y)).xyz;  
    normal = -1.0 + normal * 2.0;  
    normal.x *= 0.1;
    normal.y *= 0.1;
    return normalize(normal);  
  }

  vec4 frag () {
    float timeFactor = 0.2;
    float offsetFactor = 0.2;
    float refractionFactor = 0.4;
    
    vec3 normal = waveNormal(v_uv0 + vec2(cc_time.x * 0.1 * timeFactor, cc_time.x * 0.3 * timeFactor));
    
    vec2 p = -1.0 + 5.0 * v_uv0;  
    // 眼睛位置 位于中心点正上方 
    vec3 eyePos = vec3(0, 0, 10);  
    vec3 inVec = normalize(vec3(p, 0) - eyePos);  
    vec3 refractVec = refract(inVec, normal, refractionFactor);  //根据入射向量，法线，折射系数计算折射向量
    vec2 v_texCoordN = v_uv0;
    v_texCoordN += refractVec.xy * offsetFactor;    

    vec4 o = texture(cc_spriteTexture, v_texCoordN);
    vec4 o1 = texture(cc_spriteTexture, v_uv0);
    vec4 oo = texture(highLightTexture, v_uv0);

    return smoothstep(1.0,0.0,oo.r) < 0.99 ? o : o1;
  }
}%
