id Software published no specification for MD5. The format is defined by the loader in
the Doom 3 source code, released under the GPL in 2011 (Model_md5.cpp),
which this page follows. An .md5mesh file holds the skeleton in its bind
pose and one or more meshes skinned to it.
Tokens
The file is text, read by the engine’s general tokenizer (idLexer, in
Lexer.cpp and Token.cpp). Tokens are separated by any
white space, so line breaks and indentation carry no meaning. Names and paths are in
double quotes. // starts a comment to the
end of the line and /* … */ encloses one. Vectors are numbers in
parentheses, such as ( 0 1.5 -2 ). Keywords must appear in exactly the
order below; the engine stops with an error at the first unexpected token.
Lexer details
- Keywords are case-sensitive:
ExpectTokenStringcompares withtoken != string, andidStr’s==isidStr::Cmp, not a case-blind compare (Lexer.cpp919-931,Str.h626-650).Jointsis notjoints. - An unquoted name starts with a letter or underscore, or, because of
LEXFL_ALLOWPATHNAMES, with/,\or.(ReadToken,Lexer.cpp899-904; a.followed by a digit starts a number instead, 872-873). It continues with letters, digits,_,/,\,:and.; a-is not a name character, so it ends the name (ReadName, 541-548). - Comments do not nest. Inside
/* … */the first*/closes the comment; a/*seen inside only prints the warningnested comment(ReadWhiteSpace, 327-334). After the closing*/the lexer steps over one more character before it goes on (336-340 move the pointer once on the closing/and once more), so the character straight after*/is skipped, whatever it is. Write a space or line break after*/. - A token in single quotes is a literal (
TT_LITERAL), read like a string. If it is not exactly one character long the loader prints the warningliteral is not one character longand goes on (ReadString,Lexer.cpp514-520), because these loaders do not setLEXFL_ALLOWMULTICHARLITERALS. - Keywords and brackets are matched by their text only.
ExpectTokenStringreads one token and compares its text withtoken != string, ignoring the token type (Lexer.cpp919-931), so a quoted"joints"or"{"is accepted where the bare word or bracket is expected. - White space is every character with a code up to and including the space (
while( *script_p <= ' ' ),ReadWhiteSpace,Lexer.cpp288). A NUL byte is not skipped: it ends the text, and the next token read fails withcouldn't find expected …, so anything after a NUL is never read (289-291).script_pis aconst char *(Lexer.h249), so wherecharis signed, as on common x86 compilers, bytes from 0x80 up compare as negative and also count as white space outside a string. Inside a quoted string they are ordinary characters. /*/is a complete comment. After/*the pointer moves on one character and then tests whether the current character is/with*before it (Lexer.cpp319-330); in/*/the third character is a/preceded by the*, so the comment closes there. The character after it is then skipped, as in the previous rule./**/also closes normally.
Source: id-Software/DOOM-3 neo/idlib/Lexer.cpp and Str.h, read as raw text and not run.
Number forms
The tokenizer (idLexer::ReadNumber) starts a number at a digit, or at a
. followed by a digit. It reads these forms:
| Form | Reads as | Example |
|---|---|---|
0x or 0X, then digits 0-9 a-f A-F | Hexadecimal integer | 0x1F |
0b or 0B, then 0 and 1 | Binary integer | 0b101 |
A leading 0 not followed by ., x or b, then digits 0-7 | Octal integer, so 010 is 8. The branch reads only the digits 0-7: no dot, no exponent and no float suffix. The token stops at the first other character, so 0e5 is the integer 0 followed by the name e5, 08 is 0 followed by 8, and 00.5 is 00 followed by .5 (Lexer.cpp 589-624) | 017 |
Digits and at most one ., in a number that does not begin with 0 (or begins 0.) | Decimal integer, or a float if it has the dot | 12, 1.5, .5, 0.5, 5. |
The previous row, followed by lowercase e, an optional + or -, and digits | Float with an exponent; digits alone with e (1e3) also count as a float, but only when the number does not begin with 0 (0e5 is the octal case above). A capital E is not an exponent | 1.5e-3, 1e3, 0.5e2 |
A float followed by f/F or l/L; an integer followed by up to two of l/L and u/U | The suffix is consumed and marks precision, long or unsigned | 1.5f, 7u |
1.#INF, 1.#IND, 1.#NAN, 1.#QNAN, 1.#SNAN | Float exceptions; an error unless LEXFL_ALLOWFLOATEXCEPTIONS is set, which these loaders do not set |
A number with more than one dot is an error (more than one dot in number),
because the loaders do not set LEXFL_ALLOWIPADDRESSES.
A minus sign is not part of the number. The tokenizer returns - as a
separate punctuation token and ParseInt and ParseFloat read the
number after it and negate it. White space between the - and the digits
is therefore accepted, and a vector such as ( - 2 ) parses. A leading
+ is not handled and is an error.
Integer fields (MD5Version, counts, indices, parents, joints,
startWeight, countWeight) are read with
idLexer::ParseInt. It stops with an error if the token is not a number.
After a - it demands an integer token (ExpectTokenType( TT_NUMBER, TT_INTEGER )),
so -1.5 is an error. Without a -, its test for a float is
token.subtype == TT_FLOAT, but the subtype the tokenizer gives a float also
carries the decimal and precision bits (TT_DECIMAL | TT_FLOAT | TT_DOUBLE_PRECISION),
so that test is never true for it: a positive float such as 1.5 in an
integer field is accepted and converted by idToken::NumberValue with
idMath::Ftol. Float fields accept any number token, integer forms included.
Source: id-Software/DOOM-3, neo/idlib/Lexer.cpp (ReadToken,
ReadNumber, ParseInt, ParseFloat),
neo/idlib/Token.cpp (NumberValue) and neo/idlib/Token.h
(the TT_ bits), read as raw text.
Strings and names
The mesh loader creates its lexer with LEXFL_ALLOWPATHNAMES | LEXFL_NOSTRINGESCAPECHARS
(Model_md5.cpp, LoadModel). The animation and camera loaders add
LEXFL_NOSTRINGCONCAT (Anim.cpp, Camera.cpp).
- No escapes: a backslash inside a quoted string is an ordinary character, so a name cannot contain a double quote. A string ends at the next
"; a line break or the end of the file inside it is an error (newline inside string,missing trailing quote). A single-quoted token is a literal and is read the same way. - Path names: an unquoted name starts with a letter or underscore and continues with letters, digits,
_and, because ofLEXFL_ALLOWPATHNAMES,/,\,:and.. Quoted names (as the exporter writes them) may hold anything except a quote and a line break. - Concatenation, in the mesh file only: when a closing quote is followed by white space (comments count as white space) and then another opening quote, the two are joined into one string. So
"models/" "crate"ismodels/crate. The animation and camera loaders stop at the closing quote.
Source: idLexer::ReadString and ReadName in Lexer.cpp.
Header
| Keyword | Value | Meaning |
|---|---|---|
MD5Version | integer | Always 10; any other version is refused |
commandline | string | The exporter options used to make the file; ignored when loading |
numJoints | integer | Joints in the joints block |
numMeshes | integer | Number of mesh blocks |
Joints
joints {, then one line per joint, then }. Each joint
is:
"name" parent ( x y z ) ( qx qy qz )
| Field | Type | Meaning |
|---|---|---|
| name | string | Joint name, such as "origin" or "Lknee" |
| parent | integer | Number of the parent joint, counted from 0, or any negative number for the root. ParseJoint refuses a parent number that is numJoints − 1 or more (Invalid parent for joint). It does not check that the parent comes earlier in the list |
( x y z ) | 3 floats | Position of the joint in model space |
( qx qy qz ) | 3 floats | Orientation in model space: the x, y and z parts of a unit quaternion |
The only parent check is the range test above, and a joint number of
numJoints − 1 is refused even though it is a valid joint. The loader builds the
bind pose in one pass, converting each joint against its parent’s matrix
(poseMat3[ parentNum ]), which is filled in only for joints already read; a
parent listed later is read before it is set, which the source does not guard
against, so the file must list parents first (the animation loader does enforce that
for .md5anim).
The fourth part, w, is not stored. Doom 3 computes it as
w = √|1 − qx² − qy² − qz²|, never negative. Note that mesh-file joints are
in model space, while the joints in an animation
file are relative to their parents.
Meshes
Each mesh is mesh { … } with these parts in order:
| Keyword | Value | Meaning |
|---|---|---|
name | string | Optional mesh name |
shader | string | The material, a Doom 3 material name such as "models/monsters/imp/imp". The loader looks it up with FindMaterial, whose makeDefault is true (Model_md5.cpp 119, DeclManager.h 314), so a name with no material definition is not a load error: a default material is made for it. An empty name is looked up as _emptyName (DeclManager.cpp 1117-1120). |
numverts | integer | Vertices that follow |
vert | see below | One per vertex |
numtris | integer | Triangles that follow |
tri | see below | One per triangle |
numweights | integer | Weights that follow |
weight | see below | One per weight |
Vertex
vert index ( s t ) startWeight countWeight
| Field | Type | Meaning |
|---|---|---|
| index | integer | Vertex number; read and ignored, since vertices are taken in order |
( s t ) | 2 floats | Texture coordinates, copied unchanged into the vertex’s st (Model_md5.cpp 242) and not range-checked. t = 0 is the top row of the image and t = 1 the bottom row, the Direct3D way, not the usual OpenGL bottom-up one; see Texture origin |
| startWeight | integer | Number of the vertex’s first weight |
| countWeight | integer | How many consecutive weights it uses, at least 1 |
Texture origin
The rule is t = 0 at the top row of the image as it is displayed, and t = 1 at the bottom row. s runs from the left column (0) to the right (1). It follows from five steps in the Doom 3 source, each read as raw text in this session and not run:
- The loader copies
( s t )straight into the vertex:Parse1DMatrix( 2, texCoords[ i ].ToFloatPtr() )(Model_md5.cpp140) andverts[i].st = texCoords[i](242). No1 − tis applied. - The renderer hands
stto OpenGL unchanged:qglTexCoordPointer( 2, GL_FLOAT, sizeof( idDrawVert ), … st … )(tr_render.cpp156 and 454,draw_common.cpp261, 431 and 759). LoadTGA(Image_files.cpp639-779) writes the file’s rows from the last memory row upwards:for( row = rows - 1; row >= 0; row-- )at 642 (uncompressed) and 695 (run-length). The first row in the file lands in the last memory row. A normal TGA, with bit 5 (0x20) of the descriptor clear, stores the bottom picture row first, so memory row 0 receives the top picture row.- A top-down TGA (descriptor bit 5 set) has the top picture row first, so the loop above leaves the picture upside down in memory;
if ( targa_header.attributes & (1<<5) ) R_VerticalFlip( … )(781-783) swaps the rows (Image_process.cpp592-603). Memory row 0 is again the top picture row. - The 2D upload passes the buffer to
qglTexImage2Din memory order with no flip (Image_load.cpp674 and 709 for the RGBA path, 1550 for the DDS path). The only flips in the image code are for cube maps (Image_files.cpp1145 and 1148).
OpenGL maps t = 0 to the first row in memory, which is the top of the picture, so
the engine’s t = 0 is the top row. A material stage can still change this with its own
texture transform, which is outside the model file. This was traced for TGA images only
and the source gives no other model-relevant path. Sources: id-Software/DOOM-3
neo/renderer/Model_md5.cpp, tr_render.cpp, draw_common.cpp,
Image_files.cpp, Image_process.cpp and Image_load.cpp.
Triangle
tri index v0 v1 v2
The index is read and ignored; v0, v1 and v2 are
vertex numbers in this mesh.
Checks in ParseMesh: a count below 0 is an error; a vertex with
countWeight 0 is an error (Vertex without any joint weights);
texture coordinates are not range-checked, and ParseMesh itself does not
test the triangle indices. If the highest startWeight + countWeight
is more than numweights, the loader prints a warning
(Vertices reference out of range weights) and goes on.
The triangle indices are checked later: ParseMesh passes them to
R_BuildDeformInfo, which calls R_RangeCheckIndexes
(tr_trisurf.cpp 671-690, called at line 2166). That is a fatal error for an
index below 0 or at numverts or above, and for an index count that is not
a multiple of 3 (a file cannot give a partial triangle, since each tri line
has three indices, but the rule is in the code). Degenerate and duplicate
triangles are not removed (those calls are commented out in R_BuildDeformInfo)
and are not an error. Source: id-Software/DOOM-3, neo/renderer/tr_trisurf.cpp, raw.
After the last mesh block the loader reads nothing more. Any tokens after
the numMeshesth mesh are ignored, so a file with more mesh
blocks than numMeshes loads only the first ones. The mesh loader also
does not range-check numJoints itself (a negative count is not tested in
LoadModel); numMeshes, numverts, numtris
and numweights are tested for below 0.
Winding order
The file says nothing about winding; the engine fixes it. The mesh loader passes the
triangle indices on unchanged in file order (tris[ i * 3 + 0..2 ]) to
R_BuildDeformInfo. The face-plane code (R_DeriveFacePlanes in
tr_trisurf.cpp) is compiled as #if 1 and calls
SIMDProcessor->DeriveTriPlanes; the plain C loop in its #else
branch is not compiled. idSIMD_Generic::DeriveTriPlanes
(Simd_Generic.cpp 2447-2481) takes d0 = b − a and d1 = c − a
for the three vertices a, b, c, and computes the normal
n = d1 × d0, that is (v3 − v1) × (v2 − v1), the reverse of the usual counter-clockwise rule (the
optimised SIMD implementations are other classes and were not read). The renderer
for a normal single-sided material calls glCullFace( GL_FRONT ) in a non-mirror view
(GL_Cull, tr_backend.cpp; a mirror view swaps front and back, which cancels the
mirror’s reversed winding, so the visible side is the same); none of tr_backend.cpp,
draw_common.cpp, tr_render.cpp or win_glimp.cpp
calls glFrontFace, so the OpenGL default (counter-clockwise front) applies.
Together this means the visible side of a triangle is the one from which
v0 v1 v2 run clockwise. This follows from the code read, not from a
statement in the source.
Units and axes
The files do not define units, and none of the source files read states one; the loader stores the numbers as given. The axes can be derived from the engine:
- Up is +Z: gravity is
( 0, 0, −g_gravity )(Game_local.cpp908 and 2061), with the defaultDEFAULT_GRAVITY1066 (Game_local.h685-687). - The view matrix (
R_SetViewMatrix,tr_main.cpp838-886) has the comment “convert from our coordinate system (looking down X) to OpenGL’s coordinate system (looking down -Z)”. Its flip matrix is0 0 −1 0 / −1 0 0 0 / 0 1 0 0 / 0 0 0 1(stored column by column, as OpenGL reads it): engine +X goes to GL −Z (forward), engine +Y to GL −X (left, since GL +X is right) and engine +Z to GL +Y (up).
So +X is forward, +Y is left and +Z is up, a right-handed system (X × Y = Z). Sources: id-Software/DOOM-3 neo/renderer/tr_main.cpp, neo/game/Game_local.cpp and Game_local.h, raw. This is derived from the engine code, not from a statement about model files.
Weight
weight index joint bias ( x y z )
| Field | Type | Meaning |
|---|---|---|
| index | integer | Weight number; read and ignored |
| joint | integer | Joint number, 0 to numJoints − 1 |
| bias | float | How much this weight counts. The loader neither checks nor normalises the biases: the position formula below simply sums bias × position, so a vertex whose biases do not add up to 1 is scaled |
( x y z ) | 3 floats | Position in the joint’s own space |
Computing the vertices
A vertex’s position is the sum over its weights of the weight’s position carried into model space by its joint:
position = Σ bias × ( joint.position + joint.orientation · weight.position )
countWeight weights from startWeight.The product joint.orientation · weight.position is a rotation of the
weight position by the joint’s quaternion in the engine’s row-vector convention,
described under Rotation convention below.
With the joints of the bind pose this gives the model at rest; with the joints of an animation frame it gives the animated model. The file has no normals: Doom 3 computes smooth normals and tangents from the triangles.
Rotation convention
The stored ( qx qy qz ) become a quaternion ( x y z w ) with
w = +√|1 − x² − y² − z²|: the positive root, never negative
(idQuat::CalcW, Quat.h 280-283, called at Model_md5.cpp
470; the animation loader’s idCQuat::ToQuat, Quat.h 391-394, uses the
same formula). A quaternion and its negative are the same rotation, so a file whose
true quaternion has w < 0 must be written negated.
The engine then applies the rotation to row vectors, v′ = v · R, not to column vectors:
idQuat::ToMat3(Quat.cpp70-106) fills the matrix the usual way for a column-vector product, for examplemat[0][1] = xy − wzandmat[1][0] = xy + wz(withxy = 2xyas the code computes it).idMat3 * idVec3(Matrix.h450-455) computesresult.x = mat[0].x·v.x + mat[1].x·v.y + mat[2].x·v.zand so on: the vector multiplies from the left, v · mat, which is the transpose of the column-vector product.idJointMatstores the transpose of the matrix it is given (SetRotation,JointTransform.h90-101) and multiplies it by the vector as a column (109-119), which is the same row-vector result. The vertex sum above uses this.- The loader turns the model-space joints of the mesh file into parent-relative ones as
world × parentT(Model_md5.cpp556), the same convention.
The result: for a quaternion ( 0 0 sin(θ/2) cos(θ/2) ), a rotation by θ about +Z, a vector (1, 0, 0) goes to ( cos θ, −sin θ, 0 ). A positive angle about +Z takes +X towards −Y, which is the opposite sense to the conventional q p q⁻¹ (that takes +X towards +Y). Equivalently, the engine applies the conjugate of the quaternion in the conventional formula. Seen from above (+Z towards the viewer) with +X forward and +Y left, a positive angle turns clockwise.
Checked by running a Node port of the lines above: for θ = 90° the vectors (1,0,0), (0,1,0) and (0,0,1) go to (0,−1,0), (1,0,0) and (0,0,1); the conventional q p q⁻¹ gives (0,1,0), (−1,0,0) and (0,0,1). The idMat3 and idJointMat paths agree. A 30° rotation takes (1,0,0) to (0.866025, −0.5, 0).
Worked example: a vertex with one weight on joint 0, bias 1, at
( 0 0 8 ), with joint 0 at ( 0 0 32 ) and orientation
( 0 0 0 ) (w = 1, no rotation), sits at (0, 0, 40). Two weights of 0.5 on
joints at heights 0 and 10, each with position ( 0 0 0 ), put a vertex at
height 5.