How to optimize rendering of many sphereGeometry in three.js?

こ雲淡風輕ζ 提交于 2019-12-05 00:18:06

问题


I'd like to optimize the rendering of sphereGeometry in three.js, since it becomes bottleneck in my program. The javascript program is shown as follows:

var sphereThree = [];
for(var idSphere = 0; idSphere < numSphere; idSphere++){
    var sphereGeometry = new THREE.SphereGeometry(1.0);
    var sphereMaterial = new THREE.MeshLambertMaterial({color: 'rgb(255, 0, 0)'});

    sphereThree[idSphere] = new THREE.Mesh(sphereGeometry, sphereMaterial);

    sphereThree[idSphere].position.x = x[idSphere];
    sphereThree[idSphere].position.y = y[idSphere];
    sphereThree[idSphere].position.z = z[idSphere];

    scene.add(sphereThree[idSphere]);
}

As mentioned in the folloing links:
- Animateing a Million Letters Using Three.js
- Optimizing Three.js Performance: Simulating Tens of Thousands of Independent Moving Objects
they pointed out that we should not add object individually, and better add same kind of objects at the same time, for the optimization. However, since I'm new in this field, I have no idea how to code this optimization, when using SphereGeometry.

If somebody knows how to code these with using SphereGeometry, or somebody who knows a efficient method to render many (10,000 or more) spheres, would you teach us?

Thanks!


回答1:


You can just reuse the geometry and material like this:

var sphereGeometry = new THREE.SphereGeometry(1.0);
var sphereMaterial = new THREE.MeshLambertMaterial({color: 'rgb(255, 0, 0)'});

var sphereThree = [];
for(var idSphere = 0; idSphere < numSphere; idSphere++){
    sphereThree[idSphere] = new THREE.Mesh(sphereGeometry, sphereMaterial);

    sphereThree[idSphere].position.x = x[idSphere];
    sphereThree[idSphere].position.y = y[idSphere];
    sphereThree[idSphere].position.z = z[idSphere];

    scene.add(sphereThree[idSphere]);
}



回答2:


If appearance of the spheres does not matter a lot, you can also set widthSegments and heightSegments parameters to values lower than the defaults. See documentation here.

Essentially do something like:

var sphereGeometry = new THREE.SphereGeometry(1.0, 5, 4);

Update I forgot to mention that this should be done once you try mrdoob's suggestion and you want to optimize further. The speedup is not significant.



来源:https://stackoverflow.com/questions/22028288/how-to-optimize-rendering-of-many-spheregeometry-in-three-js

工具导航Map

JSON相关