Jeremy Bernier

Merging Geometries in Three.js

June 29, 2015

Merging multiple small geometries into one single geometry is generally more performant. Rendering 150,000 cubes would be excruciatingly slow if each geometry were rendered separately.

In Three.js, the THREE.Geometry class has a merge() function that allows you to merge two geometries. Below is a function that will take in an array of meshes and return a THREE.Geometry object with the geometries combined:

function mergeMeshes (meshes) {
  var combined = new THREE.Geometry();

  for (var i = 0; i < meshes.length; i++) {
    meshes[i].updateMatrix();
    combined.merge(meshes[i].geometry, meshes[i].matrix);
  }

  return combined;
}

Here’s an example of the function in action:

var meshes = [], geometry, material, mesh;

geometry = new THREE.BoxGeometry(50,50,50);
material = new THREE.MeshLambertMaterial({color: 0xCC0000});
mesh = new THREE.Mesh(geometry, material);
meshes.push(mesh);

mesh = new THREE.Mesh(geometry, material);
mesh.position.x = 100;
meshes.push(mesh);

//merge both geometries
geometry = mergeMeshes(meshes);
mesh = new THREE.Mesh(geometry, material);
scene.add(mesh);

For this to work, the geometries you combine have to be regular geometries and not BufferGeometries.

Unfortunately if you merge a bunch of adjacent cubes, the faces they share will still exist. So if you merge 3x3x3 cubes, it’s going to look like one big box on the outside, but on the inside you’re still going to see all those little individual cubes. It is possible to remove them, but as far as I know you have to remove each face individually.

Anyways I only wrote this because all the info on Google seems to be outdated (THREE.GeometryUtils.merge has been deprecated)


Jeremy Bernier

Written by Jeremy Bernier who left the NYC rat race to travel the world, work remotely, and make the world a better place.