// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.

CCEffect %{
  techniques:
  - passes:
    - vert: vs
      frag: fs
      blendState:
        targets:
        - blend: true
      rasterizerState:
        cullMode: none
      properties:
        texture: { value: white }
        smoothness: { value: 0.4 }
        time: {value: 0}
        squares: {value: [10, 10]}
        direction: {value: [1.0, -0.5]}
}%

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;
  uniform sampler2D texture;
  uniform sampler2D texture2;
  uniform Common {
    vec2 squares;
    vec2 direction;
    float smoothness;
    float time;
  };
  float progress = time;

  in mediump vec2 v_uv0;
  in vec4 v_color;

  vec4 getFromColor(vec2 uv) {
    return texture(texture, uv);
  }
  vec4 getToColor(vec2 uv) {
    return texture(texture2, uv);
  }
  vec4 transition(vec2 p) {
      const vec2 center = vec2(0.5, 0.5);
      // 根据进度计算当前方向
      vec2 v = normalize(direction);
      v /= abs(v.x) + abs(v.y);
      float d = v.x * center.x + v.y * center.y;
      float offset = smoothness;

      // 计算当前进度
      float pr = smoothstep(-offset, 0.0, v.x * p.x + v.y * p.y - (d - 0.5 + progress * (1.0 + offset)));

      // 按照 squares 划分成小方块的坐标，squares 表示每行/列的方块数
      vec2 squarep = fract(p * squares);
      vec2 squaremin = vec2(pr / 2.0);
      vec2 squaremax = vec2(1.0 - pr / 2.0);

      // 通过 step 函数计算当前像素位置是否在当前方块内，并返回一个混合系数 a
      float a = (1.0 - step(progress, 0.0)) * step(squaremin.x, squarep.x) * step(squaremin.y, squarep.y) * step(squarep.x, squaremax.x) * step(squarep.y, squaremax.y);
      return mix(getFromColor(p), getToColor(p), a);
  }

  void main () {
      gl_FragColor = v_color * transition(v_uv0);
  }
}%
