Shader特效——“幀動畫效果”的實現 【GLSL】
阿新 • • 發佈:2019-01-27
參考自:https://www.shadertoy.com/view/lsX3Rr
iChannel0是一幅由一系列連貫動作的彩虹貓組成的影象,如下圖所示
ichannel1是任意一副背景影象
效果圖
GLSL程式碼與演算法註釋如下:
uniform float iGlobalTime; uniform sampler2D iChannel0; uniform sampler2D iChannel1; vec2 iResolution = vec2(512., 512.); void main() { vec2 p = vec2(gl_FragCoord.x/ iResolution.x, gl_FragCoord.y/ iResolution.y) ; // 背景滾動的uv vec2 uv = vec2( p.x+mod(iGlobalTime,2.0), p.y ); vec3 bg = vec3(0.0,51.0/255.0,102.0/255.0); float f = texture2D( iChannel1, uv ).x; f = f*f; bg = mix( bg, vec3(1.0), f ); float a = 0.01*sin(40.0*p.x + 40.0*iGlobalTime); float h = (a+p.y-0.3)/(0.7-0.3); // 彩虹的位置 if( p.x<0.6 && h>0.0 && h<1.0 ) { // 彩虹的寬度 h = floor( h*6.0 ); // 在不同高度繪製彩虹 bg = mix( bg, vec3(1.0,0.0,0.0), 1.0 - smoothstep( 0.0, 0.1, abs(h-5.0) ) ); bg = mix( bg, vec3(1.0,0.6,0.0), 1.0 - smoothstep( 0.0, 0.1, abs(h-4.0) ) ); bg = mix( bg, vec3(1.0,1.0,0.0), 1.0 - smoothstep( 0.0, 0.1, abs(h-3.0) ) ); bg = mix( bg, vec3(0.2,1.0,0.0), 1.0 - smoothstep( 0.0, 0.1, abs(h-2.0) ) ); bg = mix( bg, vec3(0.0,0.6,1.0), 1.0 - smoothstep( 0.0, 0.1, abs(h-1.0) ) ); bg = mix( bg, vec3(0.4,0.2,1.0), 1.0 - smoothstep( 0.0, 0.1, abs(h-0.0) ) ); } // 重新計算uv,比例和位置的調整 uv = (p - vec2(0.33,0.15)) / (vec2(1.3, 1.) - vec2(0.33,0.15)); uv = clamp( uv, 0.0, 1.0 ); // 控制彩虹貓影象的偏移, floor很重要 float ofx = floor( mod( iGlobalTime*10.0*2.0, 6.0 ) ); // 單隻彩虹貓的紋理大小 (uv offset) float ww = 31.0/200.0; // uv.y = 1.0-uv.y; // 將偏移後的uv換算到單隻彩虹貓的紋理大小,否則會把之後的彩虹貓一併顯示出來 uv.x = clamp( ( uv.x + ofx)*ww, 0.0, 1.0 ); vec4 fg = texture2D( iChannel0, uv ); vec3 col = mix( bg, fg.xyz, .8 ); gl_FragColor = vec4( col, 1.0 ); }