Creating and Loading Advanced Meshes and Geometries
local graph
Chapter 8 — Creating and Loading Advanced Meshes and Geometries
Section titled “Chapter 8 — Creating and Loading Advanced Meshes and Geometries”In this chapter, we’ll look at a couple of different ways that you can create and load advanced and complex geometries and meshes. In Chapter 5, Learning to Work with Geometries, and Chapter 6, Exploring Advanced Geometries, we showed you how to create a few advanced geometries using the built-in objects from Three.js. In this chapter, we’ll use the following two approaches to create advanced geometries and meshes:
- Geometry grouping and merging
- Loading geometries from external resources
We start with the “group and merge” approach. With this approach, we use the standard Three.js grouping (THREE.Group) and the BufferGeometryUtils.mergeBufferGeometries() function to create new objects.
Geometry grouping and merging
Section titled “Geometry grouping and merging”In this section, we’ll look at two basic features of Three.js: grouping objects together and merging multiple geometries into a single geometry. We’ll start with grouping objects.
Grouping objects together
Section titled “Grouping objects together”In some of the previous chapters, you already saw how you can group objects when working with multiple materials. When you create a mesh from a geometry using multiple materials, Three.js creates a group. Multiple copies of your geometry are added to this group, each with its own specific material. This group is returned, so it looks like a mesh that uses multiple materials. In truth, however, it is a group that contains a number of meshes.
Creating groups is very easy. Every mesh you create can contain child elements, which can be added using the add function. The effect of adding a child object to a group is that you can move, scale, rotate, and translate the parent object, and all the child objects will also be affected. When using a group, you can still refer to, modify, and position the individual geometries. The only thing you need to remember is that all positions, rotations, and translations are done relative to the parent object.
Let’s look at an example (grouping.html) in the following screenshot:
Figure 8.1 – Using a THREE.Group object to group objects together
In this example, you see a large number of cubes, which are added to the scene as a single group. Before we look at the controls and the effect of using a group, let’s have a quick look at how we’ve created this mesh:
const size = 1const amount = 5000const range = 20const group = new THREE.Group()const mat = new THREE.MeshNormalMaterial()mat.blending = THREE.NormalBlendingmat.opacity = 0.1mat.transparent = truefor (let i = 0; i < amount; i++) { const x = Math.random() * range - range / 2 const y = Math.random() * range - range / 2 const z = Math.random() * range - range / 2 const g = new THREE.BoxGeometry(size, size, size) const m = new THREE.Mesh(g, mat) m.position.set(x, y, z) group.add(m)}In this code snippet, you can see that we create a THREE.Group instance. This object is almost identical to THREE.Object3D, which is the base class of THREE.Mesh and THREE.Scene, but by itself, it doesn’t contain anything or cause anything to be rendered. In this example, we use the add function to add a large number of cubes to this scene. For this example, we’ve added the controls you can use to change the position of a mesh. Whenever you change a property using this menu, the relevant property of the THREE.Group object is changed. For instance, in the next example, you can see that when we scale this THREE.Group object, all the nested cubes get scaled as well:
Figure 8.2 – Scaling a group
If you want to experiment a bit more with the THREE.Group object, a good exercise would be to alter the example so that the THREE.Group instance itself is rotating on the x axis while the individual cubes are rotating on their y axis.
Performance impact of using THREE.Group
Before we move on to the next section where we look at merging, a quick note on performance. When you use THREE.Group, all the individual meshes inside this group are treated as individual objects, which Three.js needs to manage and render. If you’ve got a large number of objects in the scene, you’ll see a noticeable drop in performance. If you look at the top-left corner of Figure 8*.2*, you can see that with 5,000 cubes on screen, we get around 56 frames per second (FPS). Not too bad, but normally we would run at around 120 FPS.
Three.js provides an additional way where we can still control the individual meshes, but get much better performance. This is done through THREE.InstancedMesh. This object works great if you want to render a large number of objects with the same geometry but with different transformations (for example, rotation, scale, color, or any other matrix transformation).
We’ve created an example called instanced-mesh.html, which shows how this works. In this example, we render 250,000 cubes and still have great performance:
Figure 8.3 – Using an InstancedMesh object for grouping
To work with a THREE.InstancedMesh object, we create it similarly to how we created the THREE.Group instance:
const size = 1const amount = 250000const range = 20const mat = new THREE.MeshNormalMaterial()mat.opacity = 0.1mat.transparent = truemat.blending = THREE.NormalBlendingconst g = new THREE.BoxGeometry(size, size, size)const mesh = new THREE.InstancedMesh(g, mat, amount)for (let i = 0; i < amount; i++) { const x = Math.random() * range - range / 2 const y = Math.random() * range - range / 2 const z = Math.random() * range - range / 2 const matrix = new THREE.Matrix4() matrix.makeTranslation(x, y, z) mesh.setMatrixAt(i, matrix)}The main difference in creating a THREE.InstancedMesh object compared to THREE.Group is that we need to define beforehand which material and geometry we want to use and how many instances of this geometry we want to create. To position or rotate one of our instances, we need to provide the transformation using a THREE.Matrix4 instance. Luckily, we don’t need to go into the math behind matrices, since Three.js provides us with a couple of helper functions on the THREE.Matrix4 instance to define a rotation, a translation, and a couple of other transformations. In this example, we simply position each instance at a random location.
So, if you’re working with a small number of meshes (or meshes using different geometries), you should use a THREE.Group object if you want to group them together. If you’re dealing with a large number of meshes that share a geometry and material, you can use a THREE.InstancedMesh object or a THREE.InstancedBufferGeometry object for a great performance boost.
In the next section, we’ll look at merging, where you’ll combine multiple separate geometries and end up with a single THREE.Geometry object.
Merging geometries
Section titled “Merging geometries”In most cases, using groups allows you to easily manipulate and manage a large number of meshes. When you’re dealing with a very large number of objects, however, performance will become an issue since Three.js has to treat all the children of the group individually. With BufferGeometryUtils.mergeBufferGeometries, you can merge geometries together and create a combined one, so Three.js would only have to manage this single geometry. In Figure 8*.4*, you can see how this works and the effect it has on performance. If you open the merging.html example, you see a scene again with the same set of randomly distributed semi-transparent cubes, which we merged into a single THREE.BufferGeometry object:
Figure 8.4 – 500,000 geometries merged into a single geometry
As you can see, we can easily render 50,000 cubes without any drop in performance. To do this, we use the following few lines of code:
const size = 1const amount = 500000const range = 20const mat = new THREE.MeshNormalMaterial()mat.blending = THREE.NormalBlendingmat.opacity = 0.1mat.transparent = trueconst geoms = []for (let i = 0; i < amount; i++) { const x = Math.random() * range - range / 2 const y = Math.random() * range - range / 2 const z = Math.random() * range - range / 2 const g = new THREE.BoxGeometry(size, size, size) g.translate(x, y, z) geoms.push(g)}const merged = BufferGeometryUtils. mergeBufferGeometries(geoms)const mesh = new THREE.Mesh(merged, mat)In this code snippet, we create a large number of THREE.BoxGeometry objects, which we merge together using the BufferGeometryUtils.mergeBufferGeometries(geoms) function. The result is a single large geometry, which we can add to the scene. The biggest drawback is that you lose control over the individual cubes since they are all merged into a single large geometry. If you want to move, rotate, or scale a single cube, you can’t (unless you search for the correct faces and vertices and position them individually).
Creating new geometries through Constructive Solid Geometry
Besides merging geometries in the way we saw in this chapter, we can also create geometries using Constructive Solid Geometry (CSG). With CSG, you can apply operations (usually addition, subtraction, difference, and intersection) to combine two geometries. These libraries would create a new geometry, based on the chosen operation. For instance, with CSG, it is very easy to create a solid cube with a sphere-like indentation on one side. Two libraries that you can use for this with Three.js are three-bvh-csg (https://github.com/gkjohnson/three-bvh-csg) and Three.csg (https://github.com/looeee/threejs-csg).
With the grouping and merging approach, you can create large and complex geometries using the basic geometries provided by Three.js. If you want to create more advanced geometries, then using the programmatic approach provided by Three.js isn’t always the best and easiest option. Three.js, luckily, offers a couple of other options to create geometries. In the next section, we’ll look at how you can load geometries and meshes from external resources.
Loading geometries from external resources
Section titled “Loading geometries from external resources”Three.js can read a large number of 3D file formats and import geometries and meshes defined in those files. A note here is that not all the features of these formats are always supported. So, sometimes there might be an issue with the textures, or materials might not be set up correctly. The new de facto standard for exchanging models and textures is glTF, so if you want to load externally created models, exporting those models to glTF format will usually give you the best results in Three.js.
In this section, we’ll dive a bit deeper into some of the formats that are supported by Three.js, but we won’t show you all the loaders. The following list shows an overview of the formats supported by Three.js:
- AMF: AMF is another 3D printing standard, but isn’t under active development anymore. The following Wikipedia page has additional information on this standard: https://www.sculpteo.com/en/glossary/amf-definition/.
- 3DM: 3DM is the format used by Rhinoceros, which is a tool to create 3D models. More information on Rhinoceros can be found here: https://www.rhino3d.com/.
- 3MF: 3MF is one of the standards used in 3D printing. Information about this format can be found on the 3MF Consortium home page: https://3mf.io.
- COLLAborative Design Activity (COLLADA): COLLADA is a format for defining digital assets in an XML-based format. This is a widely used format that is supported by pretty much all 3D applications and rendering engines.
- Draco: Draco is a file format for storing geometries and point clouds in a very efficient way. It specifies how these elements are best compressed and decompressed. Details about how Draco works can be found on its GitHub page: https://github.com/google/draco.
- GCode: GCode is a standard way of talking to 3D printers or CNC machines. When a model is printed, one of the ways a 3D printer can be controlled is by sending it GCode commands. The details of this standard are described in the following paper: https://www.nist.gov/publications/nist-rs274ngc-interpreter-version-3?pub_id=823374.
- glTF: This is a specification that defines how 3D scenes and models can be exchanged and loaded by different applications and tools and is becoming the standard format for exchanging models on the web. They come in a binary format with the
.glbextension and a text-based format with the.gltfextension. More information on this standard can be found here: https://www.khronos.org/gltf/. - Industry Foundation Classes (IFC): This is an open file format used by building information modeling (BIM) tools. It contains a model of a building and a lot of additional information on the materials used. More information about this standard can be found here: https://www.buildingsmart.org/standards/bsi-standards/industry-foundation-classes/.
- JSON: Three.js has its own JSON format that you can use to declaratively define a geometry or a scene. Even though this isn’t an official format, it’s very easy to use and comes in very handy when you want to reuse complex geometries or scenes.
- KMZ: This is the format used for 3D assets on Google Earth. More information can be found here: https://developers.google.com/kml/documentation/kmzarchives.
- LDraw: LDraw is an open standard you can use to create virtual LEGO models and scenes. More information can be found on the LDraw home page: https://ldraw.org.
- LWO: This is the file format used by LightWave 3D. More information on LightWave 3D can be found here: https://www.lightwave3d.com/.
- NRRD: NRRD is a file format used to visualize volumetric data. It can, for instance, be used to render CT scans. A lot of information and samples can be found here: http://teem.sourceforge.net/nrrd/.
- OBJ and MTL: OBJ is a simple 3D format first developed by Wavefront Technologies. It’s one of the most widely adopted 3D file formats and is used to define the geometry of an object. MTL is a companion format to OBJ. In an MTL file, the material of the objects in an OBJ file is specified. Three.js also has a custom OBJ exporter, called
OBJExporter, should you want to export your models to OBJ from Three.js. - PCD: This is an open format for describing point clouds. More information can be found here: https://pointclouds.org/documentation/tutorials/pcd_file_format.html.
- PDB: This is a very specialized format, created by Protein Data Bank (PDB), which is used to specify what proteins look like. Three.js can load and visualize proteins specified in this format.
- Polygon File Format (PLY): This is most often used to store information from 3D scanners.
- Packed Raw WebGL Model (PRWM): This is another format focusing on the efficient storage and parsing of 3D geometries. More information on this standard and how you can use it is described here: https://github.com/kchapelier/PRWM.
- STereoLithography (STL): This is widely used for rapid prototyping. For instance, models for 3D printers are often defined as STL files. Three.js also has a custom STL exporter, called
STLExporter.js, should you want to export your models to STL from Three.js. - SVG: SVG is a standard way to define vector graphics. This loader allows you to load an SVG file and returns a set of
THREE.Pathelements that you can use for extruding or rendering in 2D. - 3DS: The Autodesk 3DS format. More information can be found at https://www.autodesk.com/.
- TILT: TILT is the format used by Tilt Brush, a VR tool that allows you to paint in VR. More information is available here: https://www.tiltbrush.com/.
- VOX: The format used by MagicaVoxel, a free tool you can use to create voxel art. More information is available on the home page of MagicaVoxel: https://ephtracy.github.io/.
- Virtual Reality Modeling Language (VRML): This is a text-based format that allows you to specify 3D objects and worlds. It has been superseded by the X3D file format. Three.js doesn’t support loading X3D models, but these models can be easily converted to other formats. More information can be found at http://www.x3dom.org/?page_id=532#.
- Visualization Toolkit (VTK): This is the file format defined by and used to specify vertices and faces. There are two formats available: a binary one and a text-based ASCII one. Three.js only supports the ASCII-based format.
- XYZ: This is a very simple file format for describing points in 3D space. More information is available here: https://people.math.sc.edu/Burkardt/data/xyz/xyz.html.
In Chapter 9, Animations and Moving the Camera, we’ll revisit some of these formats (and look at a number of additional ones) when we look at animations.
As you can see from this list, Three.js supports a very large number of 3D file formats. We won’t be describing all of them, just the most interesting ones. We’ll start with the JSON loader since that provides a nice way to store and retrieve scenes you’ve created yourself.
Saving and loading in Three.js JSON format
Section titled “Saving and loading in Three.js JSON format”You can use the Three.js JSON format for two different scenarios in Three.js. You can use it to save and load a single THREE.Object3D object (which means you can also use it to export a THREE.Scene object).
To demonstrate saving and loading, we created a simple example based on THREE.TorusKnotGeometry. With this example, you can create a torus knot, just as we did in Chapter 5*,* and, using the save button from the Save/load menu, you can save the current geometry. For this example, we save using the HTML5 local storage API. This API allows us to easily store persistent information in the client’s browser and retrieve it at a later time (even after the browser has been shut down and restarted):
Figure 8.5 – Showing the loaded and the current mesh
In the previous screenshot, you can see two meshes—the red one is the one we loaded, and the yellow one is the original one. If you open this example yourself and click the save button, the current state of the mesh will be stored. Now, you can refresh the browser and click load, and the saved state will be shown in red.
Exporting in JSON from Three.js is very easy and doesn’t require you to include any additional libraries. The only thing you need to do is to export THREE.Mesh as JSON and store it in the browser’s localstorage, as follows:
const asJson = mesh.toJSON()localStorage.setItem('json', JSON.stringify(asJson))Before saving it, we first convert the result from the toJSON function (a JavaScript object) to a string using the JSON.stringify function. To save this information using the HTML5 local storage API, all we have to do is call the localStorage.setItem function. The first argument is the key value (json) that we can later use to retrieve the information we passed in as the second argument.
This JSON string looks like this:
{ "metadata": { "version": 4.5, "type": "Object", "generator": "Object3D.toJSON" }, "geometries": [ { "uuid": "15a98944-91a8-45e0-b974-0d505fcd12a8", "type": "TorusKnotGeometry", "radius": 1, "tube": 0.1, "tubularSegments": 200, "radialSegments": 10, "p": 6, "q": 7 } ], "materials": [ { "uuid": "38e11bca-36f1-4b91-b3a5-0b2104c58029", "type": "MeshStandardMaterial", "color": 16770655, // left out some material properties "stencilFuncMask": 255, "stencilFail": 7680, "stencilZFail": 7680, "stencilZPass": 7680 } ], "object": { "uuid": "373db2c3-496d-461d-9e7e-48f4d58a507d", "type": "Mesh", "castShadow": true, "layers": 1, "matrix": [ 0.5, ... 1 ], "geometry": "15a98944-91a8-45e0-b974-0d505fcd12a8", "material": "38e11bca-36f1-4b91-b3a5-0b2104c58029" }}As you can see, Three.js saves all the information about the THREE.Mesh object. Loading THREE.Mesh back into Three.js also requires just a few lines of code, as follows:
const fromStorage = localStorage.getItem('json')if (fromStorage) { const structure = JSON.parse(fromStorage) const loader = new THREE.ObjectLoader() const mesh = loader.parse(structure) mesh.material.color = new THREE.Color(0xff0000) scene.add(mesh)}Here, we first get the JSON from local storage using the name we saved it with (json, in this case). For this, we use the localStorage.getItem function provided by the HTML5 local storage API. Next, we need to convert the string back to a JavaScript object (JSON.parse) and convert the JSON object back to THREE.Mesh. Three.js provides a helper object called THREE.ObjectLoader, which you can use to convert JSON to THREE.Mesh. In this example, we used the parse method on the loader to directly parse a JSON string. The loader also provides a load function, where you can pass the URL to a file containing the JSON definition.
As you can see here, we only saved a THREE.Mesh object, so we lose everything else. If you want to save the complete scene, including the lights and the cameras, you can use the same approach to export a scene:
const asJson = scene.toJSON()localStorage.setItem('scene', JSON.stringify(asJson))The result of this is a complete scene description in JSON:
Figure 8.6 – Exporting a scene to JSON
This can be loaded in the same way as we already showed for a THREE.Mesh object. While storing your current scene and objects in JSON comes in very handy when you’re working exclusively in Three.js, this isn’t a format that can easily be exchanged with or created by other tools and programs. In the next section, we’ll look a bit deeper into some of the 3D formats supported by Three.js.
Importing from 3D file formats
Section titled “Importing from 3D file formats”At the beginning of this chapter, we listed a number of formats that are supported by Three.js. In this section, we’ll quickly walk through a few examples of those formats.
The OBJ and MTL formats
Section titled “The OBJ and MTL formats”OBJ and MTL are companion formats and are often used together. An OBJ file defines the geometry, and an MTL file defines the materials that are used. Both OBJ and MTL are text-based formats. A part of an OBJ file looks like this:
v -0.032442 0.010796 0.025935v -0.028519 0.013697 0.026201v -0.029086 0.014533 0.021409usemtl Materials 1f 2731 2735 2736 2732f 2732 2736 3043 3044An MTL file defines materials, as follows:
newmtl MaterialNs 56.862745Ka 0.000000 0.000000 0.000000Kd 0.360725 0.227524 0.127497Ks 0.010000 0.010000 0.010000Ni 1.000000d 1.000000illum 2The OBJ and MTL formats are well supported by Three.js, so this is a good format to choose if you want to exchange 3D models. Three.js has two different loaders you can use. If you only want to load the geometry, you use OBJLoader. We used this loader for our example (load-obj.html). The following screenshot shows this example:
Figure 8.7 – OBJ model that just defines the geometry
Loading an OBJ model from an external file is done like this:
import { OBJLoader } from 'three/examples/jsm/ loaders/OBJLoader'new OBJLoader().loadAsync('/assets/models/ baymax/Bigmax_White_OBJ.obj').then((model) => { model.scale.set(0.05, 0.05, 0.05) model.translateY(-1) visitChildren(model, (child) => { child.receiveShadow = true child.castShadow = true }) return model})In this code, we use OBJLoader to load the model from a URL asynchronously. This returns a JavaScript promise, which, when resolved, will contain the mesh. Once the model is loaded, we do some fine-tuning and make sure the model casts shadows and receives shadows as well. Besides loadAsync, each loader also provides a load function, which, instead of working with promises, works with callbacks. This same code would then look something like this:
const model = new OBJLoader().load('/assets/models/baymax /Bigmax_White_OBJ.obj', (model) => { model.scale.set(0.05, 0.05, 0.05) model.translateY(-1) visitChildren(model, (child) => { child.receiveShadow = true child.castShadow = true }) // do something with the model scene.add(model)})In this chapter, we’ll use the Promise -based loadAsync approach, since that avoids having nested callbacks and makes it a bit easier to chain these kinds of calls together. The next example (oad-obj-mtl.html) uses OBJLoader, together with MTLLoader, to load a model and directly assign a material. The following screenshot shows this example:

Figure 8.8 – OBJ.MTL model with a model and materials
Using an MTL file besides the OBJ file follows the same principle we saw earlier in this section:
const model = mtlLoader.loadAsync('/assets/models/butterfly/ butterfly.mtl').then((materials) => { objLoader.setMaterials(materials) return objLoader.loadAsync('/assets/models/butterfly/ butterfly.obj').then((model) => { model.scale.set(30, 30, 30) visitChildren(model, (child) => { // if there are already normals, we can't merge vertices child.geometry.deleteAttribute('normal') child.geometry = BufferGeometryUtils. mergeVertices(child.geometry) child.geometry.computeVertexNormals() child.material.opacity = 0.1 child.castShadow = true }) const wing1 = model.children[4] const wing2 = model.children[5] [0, 2, 4, 6].forEach(function (i) { model.children[i].rotation.z = 0.3 * Math.PI }) [1, 3, 5, 7].forEach(function (i) { model.children[i].rotation.z = -0.3 * Math.PI }) wing1.material.opacity = 0.9 wing1.material.transparent = true wing1.material.alphaTest = 0.1 wing1.material.side = THREE.DoubleSide wing2.material.opacity = 0.9 wing2.material.depthTest = false wing2.material.transparent = true wing2.material.alphaTest = 0.1 wing2.material.side = THREE.DoubleSide return model })})The first thing to mention before we look at the code is that if you receive an OBJ file, an MTL file, and the required texture files, you’ll have to check how the MTL file references the textures. These should be referenced relative to the MTL file and not as an absolute path. The code itself isn’t that different than the one we saw for THREE.ObjLoader. The first thing we do is load the MTL file with a THREE.MTLLoader object and the loaded materials are set in THREE.ObjLoader through the setMaterials function.
The model we’ve used as an example, in this case, is complex. So, we set some specific properties in the callback to fix a number of rendering issues, as follows:
- We needed to merge the vertices in the model so that it is rendered as a smooth model. For this, we first needed to remove the already defined
normalvectors from the loaded model so that we could use theBufferGeometryUtils.mergeVerticesandcomputeVertexNormalsfunctions to provide Three.js with the information to correctly render the model. - The opacity in the source files was set incorrectly, which caused the wings to be invisible. So, to fix that, we set the
opacityandtransparentproperties ourselves. - By default, Three.js only renders one side of an object. Since we look at the wings from two sides, we needed to set the
sideproperty to theTHREE.DoubleSidevalue. - The wings caused some unwanted artifacts when they needed to be rendered on top of one another. We fixed that by setting the
alphaTestproperty.
But as you can see, you can easily load complex models directly into Three.js and render them in real time in your browser. You might need to fine-tune various material properties, though.
Loading a gLTF model
Section titled “Loading a gLTF model”We already mentioned that glTF is a great format to use when importing data in Three.js. Just to show you how easy it is to import and show even complex scenes, we’ve added an example where we just took a model from https://sketchfab.com/3d-models/sea-house-bc4782005e9646fb9e6e18df61bfd28d:

Figure 8.9 – Complex 3D scene loaded from glTF with Three.js
As you can see from the previous screenshot, this isn’t a simple scene but a complex one, with lots of models, textures, shadows, and other elements. To get this in Three.js, all we had to do was this:
const loader = new GLTFLoader()return loader.loadAsync('/assets/models/sea_house/ scene.gltf').then((structure) => { structure.scene.scale.setScalar(0.2, 0.2, 0.2) visitChildren(structure.scene, (child) => { if (child.material) { child.material.depthWrite = true } }) scene.add(structure.scene)})You’re already familiar with the async loader, and the only thing we needed to fix was to make sure the depthWrite property of the materials was set correctly (this seems to be a common issue with some glTF models). And that’s it—it just works. glTF also allows us to define animations, which is something we’ll look at a bit closer in the next chapter.
Showing complete LEGO models
Section titled “Showing complete LEGO models”Besides 3D models, where the model defines the vertices, materials, lights, and more, there are also various file formats that don’t explicitly define the geometries but have more specific usage. The LDrawLoader loader, which we’ll be looking at in this section, was created to render LEGO models in 3D. Using this loader works in the same way as we’ve already seen a couple of times:
loader.loadAsync('/assets/models/lego/10174-1-ImperialAT-ST-UCS.mpd_Packed.mpd').'/assets/models/lego/10174-1-ImperialAT-ST-UCS.mpd_Packed.mpd'.then((model) => { model.scale.set(0.015, 0.015, 0.015) model.rotateZ(Math.PI) model.rotateY(Math.PI) model.translateY(1) visitChildren(model, (child) => { child.castShadow = true child.receiveShadow = true }) scene.add(model))})And the results look really great:

Figure 8.10 – LEGO Imperial AT-ST model
As you can see, it shows the complete structure of a LEGO set. There are many different models out there that you can use:

Figure 8.11 – LEGO X-Wing Fighter
If you want to explore more models, you can download them from the LDraw repository: https://omr.ldraw.org/.
Loading voxel-based models
Section titled “Loading voxel-based models”Another interesting approach to creating 3D models is by using voxels. This allows you to build models using small cubes and render them using Three.js. For instance, you can create Minecraft structures outside of Minecraft using such a tool and import them into Minecraft at a later time. A free tool to experiment with voxels is MagicaVoxel (https://ephtracy.github.io/). This tool allows you to create voxel models such as this:

Figure 8.12 – Example model created with MagicaVoxel
The interesting part is that you can easily import these models in Three.js using the VOXLoader loader, like so:
new VOXLoader().loadAsync('/assets/models/vox/monu9.vox').then((chunks) => { const group = new THREE.Group() for (let i = 0; i < chunks.length; i++) { const chunk = chunks[i] const mesh = new VOXMesh(chunk) mesh.castShadow = true mesh.receiveShadow = true group.add(mesh) } group.scale.setScalar(0.1) scene.add(group)})In the models folder, you can find a couple of vox models. The following screenshot shows what it looks like loaded with Three.js:

Figure 8.13 – Vox model loading with Three.js
The next loader is another very specific one. We’ll look at how to render proteins from PDB format.
Showing proteins from PDB
Section titled “Showing proteins from PDB”The PDB website (www.rcsb.org) contains detailed information about many different molecules and proteins. Besides an explanation of these proteins, it also provides a way to download the structure of these molecules in PDB format. Three.js provides a loader for files specified in the PDB format. In this section, we’ll give an example of how you can parse PDB files and visualize them with Three.js.
With this loader included, we’re going to create the following 3D model of the molecule description provided (see the load-pdb.html example):

Figure 8.14 – Visualizing a protein using Three.js and PDBLoader
Loading a PDB file is done in the same manner as the previous formats, as follows:
PDBLoader().loadAsync('/assets/models/molecules/caffeine.pdb').then((geometries) => { const group = new THREE.Object3D() // create the atoms const geometryAtoms = geometries.geometryAtoms for (let i = 0; i < geometryAtoms.attributes. position.count; i++) { let startPosition = new THREE.Vector3() startPosition.x = geometryAtoms.attributes. position.getX(i) startPosition.y = geometryAtoms.attributes. position.getY(i) startPosition.z = geometryAtoms.attributes.position.getZ(i) let color = new THREE.Color() color.r = geometryAtoms.attributes.color.getX(i) color.g = geometryAtoms.attributes.color.getY(i) color.b = geometryAtoms.attributes.color.getZ(i) let material = new THREE.MeshPhongMaterial({ color: color }) let sphere = new THREE.SphereGeometry(0.2) let mesh = new THREE.Mesh(sphere, material) mesh.position.copy(startPosition) group.add(mesh) } // create the bindings const geometryBonds = geometries.geometryBonds for (let j = 0; j < geometryBonds.attributes.position.count; j += 2) { let startPosition = new THREE.Vector3() startPosition.x = geometryBonds.attributes. position.getX(j) startPosition.y = geometryBonds.attributes.position. getY(j) startPosition.z = geometryBonds.attributes.position. getZ(j) let endPosition = new THREE.Vector3() endPosition.x = geometryBonds.attributes.position. getX(j + 1) endPosition.y = geometryBonds.attributes.position. getY(j + 1) endPosition.z = geometryBonds.attributes.position. getZ(j + 1) // use the start and end to create a curve, and use the curve to draw // a tube, which connects the atoms let path = new THREE.CatmullRomCurve3([startPosition, endPosition]) let tube = new THREE.TubeGeometry(path, 1, 0.04) let material = new THREE.MeshPhongMaterial({ color: 0xcccccc }) let mesh = new THREE.Mesh(tube, material) group.add(mesh) } group.scale.set(0.5, 0.5, 0.5) scene.add(group)})As you can see from this example code, we instantiate a THREE.PDBLoader object and pass in the model file we want to load, and once the model is loaded, we process it. In this case, the model consists of two properties: geometryAtoms and geometryBonds. The position attributes from geometryAtoms contain the positions of the individual atoms, and the color attributes can be used to color the individual atoms. For a link between the atoms, geometryBonds is used.
Based on the position and color, we create a THREE.Mesh object and add it to a group:
let sphere = new THREE.SphereGeometry(0.2)let mesh = new THREE.Mesh(sphere, material)mesh.position.copy(startPosition)group.add(mesh)With regard to the connection between the atoms, we follow the same approach. We get the start and end positions of the connection and use those to draw the connection:
let path = new THREE.CatmullRomCurve3([startPosition, endPosition])let tube = new THREE.TubeGeometry(path, 1, 0.04)let material = new THREE.MeshPhongMaterial({ color: 0xcccccc})let mesh = new THREE.Mesh(tube, material)group.add(mesh)For the connection, we first create a 3D path using THREE.CatmullRomCurve3. This path is used as input for THREE.TubeGeometry and is used to create a connection between the atoms. All the connections and atoms are added to a group, and this group is added to the scene. There are many models you can download from PDB. For instance, the following screenshot shows the structure of a diamond:

Figure 8.15 – The structure of a diamond
In the next section, we’re looking at the support Three.js has for the PLY model, which can be used to load point cloud data.
Loading a point cloud from a PLY model
Section titled “Loading a point cloud from a PLY model”Working with the PLY format isn’t that much different than the other formats. You include the loader and handle the loaded model. For this last example, however, we’re going to do something different. Instead of rendering the model as a mesh, we’ll use the information from this model to create a particle system (see the load-ply.html example in the following screenshot):

Figure 8.16 – Point cloud loaded from a PLY model
The JavaScript code to render the preceding screenshot is actually very simple; it looks like this:
const texture = new THREE.TextureLoader().load('/assets /textures/particles/glow.png')const material = new THREE.PointsMaterial({ size: 0.15, vertexColors: false, color: 0xffffff, map: texture, depthWrite: false, opacity: 0.1, transparent: true, blending: THREE.AdditiveBlending})return new PLYLoader().loadAsync('/assets/ models/carcloud/carcloud.ply').then((model) => { const points = new THREE.Points(model, material) points.scale.set(0.7, 0.7, 0.7) scene.add(points)})As you can see, we use THREE.PLYLoader to load the model and use this geometry as input for THREE.Points. The material we use is the same as what we used for the last example in Chapter 7, Points and Sprites. As you can see, with Three.js, it is very easy to combine models from various sources and render them in different ways, all with a few lines of code.
Other loaders
Section titled “Other loaders”At the beginning of this chapter, in the Loading geometries from external resources section, we showed you a list of all the different loaders provided by Three.js. We’ve provided examples of all these in the sources for chapter-8:

Figure 8.17 – Directory showing examples of all the loaders
The source code for all these loaders follows the same patterns as we’ve seen for the loaders we have explained in this chapter. Just load the model, determine which part of the loaded model you want to show, make sure scaling and positions are correct, and add it to the scene.
Summary
Section titled “Summary”Using models from external sources isn’t that hard to do in Three.js, especially for simple models—you only have to take a few easy steps.
When working with external models, or creating them using grouping and merging, it is good to keep a couple of things in mind. The first thing you need to remember is that when you group objects, they remain available as individual objects. Transformations applied to the parent also affect the children, but you can still transform the children individually. Besides grouping, you can also merge geometries together. With this approach, you lose the individual geometries and get a single new geometry. This is especially useful when you’re dealing with thousands of geometries you need to render and you’re running into performance issues. The final approach if you want to control a large number of meshes of the same geometry is to use a THREE.InstancedMesh object or a THREE.InstancedBufferGeometry object, which allows you to position and transform the individual meshes, but still get great performance.
Three.js supports a large number of external formats. When using these format loaders, it’s a good idea to look through the source code and add console.log statements to determine what the data loaded really looks like. This will help you to understand the steps you need to take to get the correct mesh and set it to the correct position and scale. Often, when the model doesn’t show correctly, this is caused by its material settings. It could be that incompatible texture formats are used, opacity is incorrectly defined, or the format contains incorrect links to the texture images. It is usually a good idea to use a test material to determine whether the model itself is loaded correctly and log the loaded material to the JavaScript console to check for unexpected values.
If you want to reuse your own scenes or models, you can simply export these by just calling the asJson function and loading them again with ObjectLoader.
The models you worked with in this chapter, and in the previous chapters, are mostly static models. They aren’t animated, don’t move around, and don’t change shape. In Chapter 9, you’ll learn how you can animate your models to make them come to life. Besides animations, the next chapter will also explain the various camera controls provided by Three.js. With a camera control, you can move, pan, and rotate the camera around your scene.