three.js淡入/淡出后处理着色器

时间:2014-12-24 10:56:00

标签: three.js shader fadein fadeout post-processing

我想将场景淡入灰度,但这也适用于我想淡入或淡出的其他后期处理效果。

所以对于这个例子我使用THREE.ColorifyShader,但是当激活它时,整个场景立即收到预期的颜色

如何将“opacity / alpha”应用于后期处理?

代码示例:

var effectColorify,
    copyPass;

    effectColorify = new THREE.ShaderPass(THREE.ColorifyShader);
    effectColorify.uniforms['color'].value.setRGB(0.8, 0.8, 0.8); // Grayscale

    copyPass = new THREE.ShaderPass(THREE.CopyShader);
    copyPass.renderToScreen = true;

    this.composerGrayscale = new THREE.EffectComposer(this.engine.renderer);
    this.composerGrayscale.addPass(this.renderPass);
    this.composerGrayscale.addPass(effectColorify);
    this.composerGrayscale.addPass(copyPass);

2 个答案:

答案 0 :(得分:0)

您可以添加计时器以缓慢增加RGB值。或者在渲染循环中添加它,我将使用一个计时器,但可以在渲染函数中应用完全相同的循环。

var interval = 200; //interval for the animation in ms
var darkness = 1; //we'll start with a fade in, so we need the darknes at its biggest value
var fade = 'in';

var effectTimer = setInterval(function(){
    switch(fade){

        case 'in':
            if(darkness > 0){
                darkness -= 0.1;
            }
            else{
                fade = 'off';
            }
        break;

        case 'out':
            if(darkness < 1){
                darkness += 0.1;
            }
            else{
                fade = 'off';
            }
        break;
    }
    effectColorify.uniforms['color'].value.setRGB(darkness, darkness, darkness);
}, interval)

答案 1 :(得分:0)

我通过在colorify着色器中添加“不透明度”制服解决了这个问题。这样可以通过增加不透明度或其他方式将正常的彩色场景平滑地混合到某种颜色。

effectColorify.uniforms['opacity'].value = 0.5; // 50% scene-color, 50% shader-color.

以下是您可以复制到ColorifyShader.js中的经过调整的着色器代码,该代码向后兼容以前的版本,因为默认不透明度为1.0:

THREE.ColorifyShader = {

    uniforms: {

        "tDiffuse": { type: "t", value: null },
        "color":    { type: "c", value: new THREE.Color( 0xffffff ) },
        "opacity":  { type: "f", value: 1.0 }

    },

    vertexShader: [

        "varying vec2 vUv;",

        "void main() {",

            "vUv = uv;",
            "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",

        "}"

    ].join("\n"),

    fragmentShader: [

        "uniform float opacity;",
        "uniform vec3 color;",
        "uniform sampler2D tDiffuse;",

        "varying vec2 vUv;",

        "void main() {",

            "vec4 texel = texture2D( tDiffuse, vUv );",

            "vec3 luma = vec3( 0.299, 0.587, 0.114 );",
            "float v = dot( texel.xyz, luma );",

            "vec3 finalColor = vec3(",
                "(opacity * v * color.x) + ((1.0 - opacity) * texel.x),",
                "(opacity * v * color.y) + ((1.0 - opacity) * texel.y),",
                "(opacity * v * color.z) + ((1.0 - opacity) * texel.z)",
            ");",

            "gl_FragColor = vec4( finalColor, texel.w );",

        "}"

    ].join("\n")

};