cocos shader 初探之马赛克

1.效果

2.原理

        将一张图片分割成n*n个格子,将得到的uv判断出所在的格子,将uv坐标偏移到格子的中间。 

3.代码

// 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 }
        alphaThreshold: { value: 0.5 }
        mosaic_factor: { 
          value: 10,
          editor: {
            tooltip: '马赛克数量系数'
          }
        }
}%


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>
  #include <texture>

  in vec4 v_color;

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


  uniform Constant{
    float mosaic_factor;
  };

  /**
  * 得到马赛克的uv坐标
  */
  vec2 getMosaicUV(vec2 uv) { 
    float mosaic = 1.0 / mosaic_factor;
    if(mosaic<=0.0){
      mosaic = 1.0;
    }
    //计算新的uv
    uv.x = floor(uv.x / mosaic)*mosaic + mosaic *0.5;
    uv.y = floor(uv.y / mosaic)*mosaic + mosaic *0.5;

    return uv;
  }

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


    vec2 mosaic_uv = getMosaicUV(v_uv0);
    #if USE_TEXTURE
      CCTexture(texture, mosaic_uv, o);
    #endif

    o *= v_color;

    ALPHA_TEST(o);

    gl_FragColor = o;
  }
}%

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值