A model is a file exported from a 3D modeling package such as 3D Studio Max or Blender. The file basically contains a list of points called vertices, which form the edges of polygons that, joined together, give the appearance of a smooth surface:
To load a model, we must add it to our game's content project. XNA will automatically build all of the content in our content project so that we can use it in our game. To add a model to the content project, open the Solution Explorer, right-click on the content project (labeled Content), and click on Add Existing Item.
In addition to building all of the content in the content project, XNA builds any files referenced by a piece of content. Because our model references its texture, we need to exclude the texture from the list of content to build or it will be built twice. Right-click on the texture and then select Exclude From Project. This will remove the texture from the content project but will not delete the file itself, which will allow XNA to find it when building the model but still only build it once.
Now that the content pipeline is building our model for us, we can load it into our game. We do this with the ContentManager
class—a class used to access the runtime functionality of the content pipeline. The Game
class already has an instance of the ContentManager
class built-in, so we can go ahead and use it in the LoadContent()
method.
First, an instance of the Model
class will be needed. The Model
class contains all the data necessary to draw and work with a model. We will also need an array of matrices representing the model's built-in mesh transformations. Add the following member definitions:
Model model; Matrix[] transforms;
Now, in the LoadContent()
method, we can use the ContentManager
to load the model. The Load()
function of the ContentManager
class takes the name of the resource to load—the original filename without its extension. Note that this means we can't have multiple files with the same name only varying by extension.
model = Content.Load<Model>("ship"); transforms = new Matrix[model.Bones.Count]; model.CopyAbsoluteBoneTransformsTo(transforms);
In XNA, a model is made up of pieces called
meshes. As described earlier, each model has its own transformation in 3D space, and each mesh also has its own transformation relative to the model's transformation as a whole. The Model
class stores these transformations as a skeleton structure with each mesh attached to a bone. The last two lines in the previous code snippet copied that skeleton into the transforms
array.