# How to draw spheres more than 1000000?

Recently, I used the below code to visualize some kinds of molecule structure.

``````var geometry = new THREE.SphereBufferGeometry(r, segmentNum, segmentNum);
var vertexNum = geometry.getAttribute("position").count;
var vertexColor = new Float32Array(vertexNum*3);
for (var i = 0; i < vertexNum*3; i+=3){
vertexColor[i] = rgbColor;
vertexColor[i+1] = rgbColor;
vertexColor[i+2] = rgbColor;
}
geometry.addAttribute("color", new THREE.BufferAttribute(vertexColor, 3));
var material = new THREE.MeshPhongMaterial({color: atomColor, shininess: 30});
var mesh = new THREE.Mesh(geometry, material);
``````

However, as the number of atoms increases more than 10000, the browser will crash and alert an error that “Page no response!”. For the demand of some cheminformatic experiment, we need to visualize atoms more than 1000000. So I wonder if there are any possible solutions to this problem. Thanks for your attention~

You’ll want to use `InstancedMesh`, so that you can render many objects with a single call to the GPU, instead of one call to the GPU per object. See the following:

Three.js builtin `InstancedMesh` class:

The three-instanced-mesh lib, with a few extra features:

Examples on how instancing works (note the large number of objects drawing on screen):

The basic concept is that you draw many objects at once, as if they were all a single mesh (one GPU call means the GPU draws one set of vertices for all of your “objects” as if they were a single object).

2 Likes

However, the radius and the color of the atoms are different from each other. Can this situation still uses InstancedMesh?

Even if you’d instance all these Spheres, it’ll either crash or run at 0.01fps - you’d be trying to render 1mil * (segmentNum^2) faces at once.

I’d try to use some smart math and determine how many atoms are actually visible at a given moment + how many of those would have sub-pixel size. Then use pooling / instancing to render only these that are visible - rest can either be hidden or approximated in groups using some simplified geometry.

1 Like

May also try pure glsl RayMarching and SDF algorithms, with these algorithms you just need add a mod or fract or similar to repeat objects.
No matter how many objects, the algorithm complexity is the same, but with a lot of limitations though.

2 Likes

You can render spheres as pixel perfect round spheres using points with the least cost possible without raymarching. But the limit for a stable 60 fps depends on the device at the end, i could render in a test 20 million without issue for sphere based particles on my machine.

I’m quite sure someone already made an example for lit spheres but i can’t find right now i’m on mobile.

Recommend reading that thread and look in the forum as it has been a topic before.

3 Likes

Check out the APIs!