Shader 动画——实现跳动的心

最终效果:

本Shader算法参考自Shadertoy, 原地址:https://www.shadertoy.com/view/XsfGRn

Shader的实现:
vs: heart.vert

attribute vec4 a_position;
attribute vec2 a_texCoord;

#ifdef GL_ES
varying lowp vec2 v_texCoord;
#else
varying vec2 v_texCoord;
#endif

void main()
{
    gl_Position = CC_PMatrix * a_position;
    v_texCoord = a_texCoord;
}


```





ps:heart.frag

#ifdef GL_ES
varying lowp vec2 v_texCoord;
#else
varying vec2 v_texCoord;
#endif


uniform vec2 u_screenSize;//视口大小,Director::getInstance()->getVisibleSize();
//uniform vec4 u_heartColor;
uniform float u_heartColorR;//heart的RGB值
uniform float u_heartColorG;
uniform float u_heartColorB;


void main()
{
 vec4 u_heartColor = vec4(u_heartColorR, u_heartColorG, u_heartColorB, 1.);
 vec2 fragCoord = vec2(v_texCoord.x, 1-v_texCoord.y)*u_screenSize.xy;
    vec4 u_bgColor = vec4(1.0);//背景颜色
    float _Blur = 0.02;//heart边缘模糊大小
    float _Duration = 1.5;//跳动周期


    vec2 p = (2.0*fragCoord.xy-u_screenSize.xy)/min(u_screenSize.y,u_screenSize.x);
    p.y -= 0.25;


    // heart跳动算法
    float tt = mod(CC_Time.y,1.5)/1.5;
    tt = mod(CC_Time.y,_Duration)/_Duration;
    float ss = pow(tt,.2)*0.5 + 0.5;
    ss = 1.0 + ss*0.5*sin(tt*6.2831*3.0 + p.y*0.5)*exp(-tt*4.0);
    p *= vec2(0.5,1.5) + ss*vec2(0.5,-0.5);
    // heart形状算法  
    float a = atan(p.x,p.y)/3.141593;
    float r = length(p);
    float h = abs(a);
    float d = (13.0*h - 22.0*h*h + 10.0*h*h*h)/(6.0-5.0*h);
    // Color
    float s = 1.0-0.5*clamp(r/d,0.0,1.0);
    s = 0.75 + 0.75*p.x;
    s *= 1.0-0.25*r;
    s = 0.5 + 0.6*s;
    s *= 0.5+0.5*pow( 1.0-clamp(r/d, 0.0, 1.0 ), 0.1 );
    vec3 hcol = vec3(1.0,0.5*r,0.3)*s;
    hcol = u_heartColor.xyz *s;
    vec3 col = mix( u_bgColor.xyz, hcol, smoothstep( -0.01, 0.01, d - r) );
    col = mix( u_bgColor.xyz, hcol, smoothstep( -_Blur, _Blur, d - r) );


 vec4 texColor = texture2D(CC_Texture0, v_texCoord);
    gl_FragColor = texColor * vec4(col, 1.0);
}

```


2.应用Shader:

auto bg = Sprite::create("HelloWorld.png");
 bg->setPosition(winSize / 2);
 this->addChild(bg);


  auto programState = GLProgramState::getOrCreateWithGLProgram(GLProgram::createWithFilenames("shader/heart.vert", "shader/heart.frag"));
 
 //heart animation
 programState->setUniformVec2("u_screenSize", Director::getInstance()->getWinSize());
 programState->setUniformFloat("u_heartColorR", 1.0);//RGB值传入Shader
 programState->setUniformFloat("u_heartColorG", 0.0);
 programState->setUniformFloat("u_heartColorB", 0.0);


 programState->applyUniforms();
 bg->setGLProgramState(programState);

```

原文地址:http://blog.csdn.net/final5788

效果美如画,性能低成渣。

什么时候可以改善改善引擎的效率呢?
还有耗电,发热,以及基本list view的性能

frag着色器中大量的数学计算可以放到vert着色器执行

Shader toy, 顾名思义只是玩具,都是计算机图形学大神秀算法。当然不会有人用于项目