Top ↑

Loading objects with materials

Loading shiny white geometry is all well and good, but pretty much every object isn't white and shiny. To remedy this, we need to be able to load materials.

The WaveFront format specifies that material definitions should be stored in a separate .mtl file, referenced from within the .obj file. I've written a short explanation of a .mtl file below, but if you're more interested in the code, jump to here.

MTL file explanation

Here's a short sample:

# Blender MTL File: ''
# Material Count: 1
newmtl FooBar
Ns 0
Ka 0.000000 0.000000 0.000000
Kd 0.8 0.8 0.8
Ks 0.8 0.8 0.8
d 1
illum 2

It's similar to a .obj file in that each line starts with an identifier, then contains space separated values. Lines beginning with # are comments. Let's look at the other lines.

  • newmtl FooBar starts the definition of a new material, called FooBar. The definition ends when another newmtl line is found.
  • Ns defines the model's shininess with a value ranging from 0 to 100.
  • Ka is the ambient component of the material. This is the colour reflected by the object when illuminated with ambient light.
  • Kd is the diffuse component. This can be thought of as the actual colour of the object; it is the colour seen when the object is exposed to pure white light.
  • Ks is the specular component. The colour of any highlights or reflections is goverened by this value.

Kd, Ka and Ks are all RGB values, therefore have 3 values. Ns is a float ranging from 0 to 100, so only a single value is needed.

d and illum can be ignored for the purposes of this tutorial. These values define the transparency of the material and whether specular highlights should be shown respectively.

This article is helpful if you don't quite understand how materials work, and this one has the full .mtl file specification.

Using materials

Including the file

Before a .mtl file can be parsed, the .obj file needs to be able to reference both it and the materials it contains. This is achieved by adding this line to the top of the .obj file:

mtllib cube.mtl

This tells the parser to look for a file called cube.mtl in the same directory as the .obj file.

Using/applying a material to an object

Before the face (f lines) data starts for an object, a material can be applied to the following object by adding this line:

usemtl [material]

Where [material] is the name of a material in your .mtl file. Using our example file above, this would be

usemtl FooBar
f 1/2/3 4/5/6 7/8/9
f 10/11/12 13/14/15 16/17/18
...

In the next step, we'll add to our geometry only loader so it supports materials.