如何在 Three.js 中补间 10,000 多个粒子?

Jet*_*lue 2 tween three.js tween.js

我有一个THREE.Points对象,由许多(10,000+)顶点(又名粒子)组成。

然而,当我尝试补间各个粒子的位置时,我遇到了性能问题。这是预期的,因为我使用以下代码循环遍历所有粒子并为每个粒子分配一个补间。

var duration = 500;

for( var i = 0; i < particles.geometry.vertices.length; i++ ){

    // http://threejs.org/examples/css3d_sprites.html

    var currentVertex = particles.geometry.vertices[i];

    new TWEEN.Tween( currentVertex )
        .to( 
            {
                x: newVertices[i].x,
                y: newVertices[i].y,
                z: newVertices[i].z,
            },
            duration * ( Math.random() + 1 ) 
        )
        .easing( TWEEN.Easing.Exponential.InOut )
        .onUpdate( function(){

            particles.geometry.verticesNeedUpdate = true;
        })
        .start();
}
Run Code Online (Sandbox Code Playgroud)

有更好的方法来解决这个问题吗?
我不介意所有粒子是否在一次绘制调用中更新到新的中间位置。

Jet*_*lue 5

咀嚼了一段时间后就可以运行了。

解决方案是使用缓冲区几何(如此处所示)和使用 @2pha 建议的着色器的组合。

补间功能已移至顶点着色器,可以在其中伪造每个像素补间。补间函数所需的各种数据存储在 ShaderMaterial 制服和 BufferGeometry 属性中。

一些伪代码,

// Buffer Geometry

var geometry = new THREE.BufferGeometry();
geometry.addAttribute( 'position', new THREE.BufferAttribute( bPositions, 3 ) );
geometry.addAttribute( 'color', new THREE.BufferAttribute( bColors, 3 ) );
geometry.addAttribute( 'targetPosition', new THREE.BufferAttribute( bPositions2, 3 ) );


// Shader Material

var material = new THREE.ShaderMaterial({
    uniforms: {
        elapsedTime : {
            type: "f",
            value: 0.0
        },
        duration : {
            type: "f",
            value: 0.0
        }
    },
    vertexShader: document.getElementById( 'vertexShader' ).textContent,
    fragmentShader: document.getElementById( 'fragmentShader' ).textContent
});

// Vertex Shader

uniform float elapsedTime;
uniform float duration;
attribute vec3 targetPosition;

float exponentialInOut( float k ){
    // https://github.com/tweenjs/tween.js/blob/master/src/Tween.js
    if( k <= 0.0 ){
        return 0.0;
    }
    else if( k >= 1.0 ){
        return 1.0;
    }
    else if( ( k *= 2.0 ) < 1.0 ){
        return 0.5 * pow( 1024.0, k - 1.0 );
    }
    return 0.5 * ( - pow( 2.0, - 10.0 * ( k - 1.0 ) ) + 2.0 );
}

void main(){

    // calculate time value (also vary duration of each particle)
    float t = elapsedTime / ( duration * ( 1.0 + randomNum.x ) );

    // calculate progress
    float progress = exponentialInOut( t );

    // calculate new position (simple linear interpolation)
    vec3 delta = targetPosition - position;
    vec3 newPosition = position + delta * progress;

    // something
    gl_Position = projectionMatrix * modelViewMatrix * vec4( newPosition, 1.0 );
}
Run Code Online (Sandbox Code Playgroud)

  • 感谢您的帖子,我在这里实现了一个演示 https://codepen.io/timohausmann/pen/oNYeMYP (2认同)