29 March, 2017

THREE.js merging geometries

I've had some trouble working out how to properly merge Geometries in three.js so I've created an example.

Have a look at http://qazzian.com:3000/mergeTest.html

In this example, all the blocks are using the same material.

Simple merge example:
let geom1 = new THREE.BoxGeometry(1,1,1);
let geom2 = new THREE.BoxGeometry(2,1,2);

After merging the blocks THREE needs to know that shape has changed.

// Tell THREE to recalculate various things.
this.block0.elementsNeedUpdate = true;
this.block0.verticesNeedUpdate = true;
this.block0.uvsNeedUpdate = true;
this.block0.normalsNeedUpdate = true;
this.block0.colorsNeedUpdate = true;
this.block0.lineDistancesNeedUpdate = true;
this.block0.groupsNeedUpdate = true;

THREE also needs to update the render location for the camera. Otherwise all the merged blocks disappear from the view when the first block is off camera.

See source for this example is hosted on github:

The addCube function is the one that does the merging.
It uses a setTimeout to simulate data loading asynchronously.