最近在研究ThreeJS,记录一个常用的Shader。
GaussianShader代码如下:
var GaussianBlurShader = {
uniforms: {
"tDiffuse": { value: null },
"v": { value: 1.0 / 512.0 },
"h": { value: 1.0 / 512.0 }
},
vertexShader: [
"varying vec2 vUv;",
"void main() {",
" vUv = uv;",
" gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
"}"
].join( "\n" ),
fragmentShader: [
"uniform sampler2D tDiffuse;",
"uniform float v;",
"uniform float h;",
"varying vec2 vUv;",
"void main() {",
" vec4 sum = vec4( 0.0 );",
" sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y - 4.0 * v ) ) * 0.051;",
" sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y - 3.0 * v ) ) * 0.0918;",
" sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y - 2.0 * v ) ) * 0.12245;",
" sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y - 1.0 * v ) ) * 0.1531;",
" sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y ) ) * 0.1633;",
" sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y + 1.0 * v ) ) * 0.1531;",
" sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y + 2.0 * v ) ) * 0.12245;",
" sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y + 3.0 * v ) ) * 0.0918;",
" sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y + 4.0 * v ) ) * 0.051;",
" vec4 sum1 = vec4( 0.0 );",
" sum1 += texture2D( tDiffuse, vec2( vUv.x - 4.0 * h, vUv.y ) ) * 0.051;",
" sum1 += texture2D( tDiffuse, vec2( vUv.x - 3.0 * h, vUv.y ) ) * 0.0918;",
" sum1 += texture2D( tDiffuse, vec2( vUv.x - 2.0 * h, vUv.y ) ) * 0.12245;",
" sum1 += texture2D( tDiffuse, vec2( vUv.x - 1.0 * h, vUv.y ) ) * 0.1531;",
" sum1 += texture2D( tDiffuse, vec2( vUv.x, vUv.y ) ) * 0.1633;",
" sum1 += texture2D( tDiffuse, vec2( vUv.x + 1.0 * h, vUv.y ) ) * 0.1531;",
" sum1 += texture2D( tDiffuse, vec2( vUv.x + 2.0 * h, vUv.y ) ) * 0.12245;",
" sum1 += texture2D( tDiffuse, vec2( vUv.x + 3.0 * h, vUv.y ) ) * 0.0918;",
" sum1 += texture2D( tDiffuse, vec2( vUv.x + 4.0 * h, vUv.y ) ) * 0.051;",
" gl_FragColor = (sum +sum1) * 0.5;",
"}"
].join( "\n" )
};
export { GaussianBlurShader };
使用方法:
//创建一个材质
var gaussianBlurMat = new THREE.ShaderMaterial(GaussianBlurShader);
//给材质添加贴图
panelMesh.material.uniforms['tDiffuse'].value = texture;
//设置水平参数
panelMesh.material.uniforms['h'].value = 1.0 / 256.0;
//设置垂直参数
panelMesh.material.uniforms['v'].value = 1.0 / 256.0;
有不正确的地方希望有大佬指点。