Reusing three.js meshes (for voxel worlds)

1.6k views Asked by At

I'm currently learning three.js and 3D graphics for the first time and am trying to create a voxel engine (think Minecraft, Infiniminer). I'm finding that my script is taking up a lot of memory, but I have my suspicions why - every block that I create uses a new Mesh object, even if some of the blocks look the same.

I asked some people I knew whether they know of a more memory-efficient way of doing this - they suggested creating one Mesh for each type of block and using matrices to transform the Mesh for each instance of the block (they're familiar with OpenGL, but not so much three.js). Does three.js allow for something like this? If so, how would you do so and if not, are there any other alternatives?

(So far my understanding is that every item you want to render needs to be in the scene graph, so even if multiple blocks look the same you need to add multiple copies of the block (with different x, y, z coords) to the graph. I'm probably wrong.)

2

There are 2 answers

2
Chris Hawkes On

I believe they are accomplishing what you're asking in the three.js trackball controls. Check out this link here

If you have trouble viewing the source use the keyboard shortcut cntrl + u (windows)

1
Darryl_Lehmann On

Good day, just to clarify. Three.js is a wrapper for the WebGL API which is a subset of OpenGL ES 2.0 with no extensions. So OpenGL related knowledge applies here to a point, you just need to work from high to low through the Three.js source.

Now, the idea of having a base set of objects and then cloning and repositioning them is sound. There is a clone() function, essentially this is creating a whole new object for you just as if you were creating new meshes, but is a bit more accessible at runtime.

If I might offer some advice, seeing some code could help us figure out more precise optimizations for your use case. Perhaps you have some calls that could/should be pushed to the init phase, maybe memory is leaking elsewhere? Alternately, you could consider merging some of your geometry if it will remain static, either in code or a 3D modelling program. This won't reduced the polycount considerable, but certainly help simplify your scene.