Realistic Images with Mathematica

On the cover of the Spring 1994 issue of The Mathematica Journal was an image of a triceratops generated by Mathematica. It was one of those images which just floored me. I mean, this really looked like a triceratops! In that issue's Graphics Gallery section were several such pictures, including a cow and a hammerhead shark. I always wondered how these images were generated and I finally got around to figuring it out. The image above is supposed to be an F-117 Stealth Fighter. It was rendered from 3 dimensional data measured from an actual F-117. I chose it because it was the smallest such data set I could find and, therefore, placed easily on the web.

Rendering such 3D images with Mathematica is a two step process.

  1. Get the 3D data.
    Data for all sorts of objects may be downloaded from Viewpoint.
  2. Read the data into Mathematica and translate it to Graphics3D format.
    This step is fairly straightforward, if the data is in a text file. Unfortunately, most of the data files on Viewpoint are binary. However, a quite a few are in Object format (.obj) which is stored in a text file. The Mathematica routine below reads .obj files, translates to Graphics3D, and renders the image. To use it, simply place the .obj file in the Mathematica start up directory and execute ObjToGraphics3D["fileName.obj"]. The file f-117.obj was used to generate this image.
ObjToGraphics3D[s_String] := Module[
	{data, vertices, faces, polys},
	
	data = ReadList[s, Word, RecordLists -> True];
	If[data =!= $Failed,
		vertices = Map[ToExpression, Drop[#,1]& /@ 
			Select[data, First[#] == "v" &], {2}];
		faces = Drop[#,1]& /@
			Select[data, First[#] == "f" &];
		If[vertices =!= {} && faces =!= {},
			faces = If[DigitQ[faces[[1]][[1]]],
				Map[ToExpression, faces, {2}],
				Map[ToExpression[
					StringTake[#, StringPosition[#, "/"][[1]][[1]] - 1]] &,
						faces, {2}]];
			polys = 
			Polygon /@ faces /. n_Integer :> vertices[[n]];
			Show[Graphics3D[polys], Boxed -> False],
			Print[s <> " does not seem to be an Object file."]
		],
		Print[s <> " not found."]
	]
]
A word of warning: The code above does a little rudimentary error checking, but I know only the very basics about 3D Object files. It seems to work with the examples I've tried, but might not work with all. You can read the specs on 3D Object files and other formats at the 3D Object File Formats page.
[UNCA | Math Dept. | Mark's Home]