Reading glTF
OBJ is universal and readable, but it predates a lot of advances in computer graphics. In particular, it doesn't support animation. We'll read animated models in using a newer format: glTF. The name is an abbreviation of GL Transmission Format. The format is specified by the Khronos Group, which is also responsible for the OpenGL and WebGL standards.
The specification is well-documented, but understanding it takes more time than we have. Instead of building our own parser like we did with OBJ, we'll use one adapted from developer Lars Jarlvik. Paste this code in the file lib/static-gltf.ts
in your project.
This glTF loader doesn't use the Trimesh
class, but it returns a similar custom object. Read in a glTF model and generate VertexAttributes
with code like this:
const model = await Gltf.readFromUrl('directory/to/model.gltf');
const attributes = new VertexAttributes();
attributes.addAttribute('position', model.meshes[0].positions.count, 3, model.meshes[0].positions.buffer);
attributes.addAttribute('normal', model.meshes[0].normals!.count, 3, model.meshes[0].normals!.buffer);
attributes.addIndices(model.meshes[0].indices!.buffer);
const model = await Gltf.readFromUrl('directory/to/model.gltf'); const attributes = new VertexAttributes(); attributes.addAttribute('position', model.meshes[0].positions.count, 3, model.meshes[0].positions.buffer); attributes.addAttribute('normal', model.meshes[0].normals!.count, 3, model.meshes[0].normals!.buffer); attributes.addIndices(model.meshes[0].indices!.buffer);
Test that you can read in a glTF model with this code. Generate one in Blender by following these steps:
Update the path in the Gltf.readFromUrl
call to point to the exported file.
Summary
The kind of models that we want to render are too complex to manage by hand. We use a Trimesh
data structure to encapsulate the list of positions and triangle indices. This data structure defines mesh operations like computing a bounding box or converting the mesh data into compact buffers that we can send to the graphics card. Some meshes—like cylinders, cones, and spheres—are algorithmic in nature and may be generated by contorting a grid to fit their surface. Other meshes are designed in modeling programs and read in as OBJ or glTF files. As our models get more complex, we need more visual cues to understand their shape. Normal vectors tell us how a surface is oriented. For now, we color our models by their normals. A normal is derived from an individual triangle by taking the cross product of two tangent vectors. These face normals are averaged together to give each vertex its own normal.